package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.ExcelConstant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasProcessRelatedDataEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.DateTimeEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.DownloadExcelTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.RelativeProductImportEnum;
import com.xbongbong.paas.enums.StarEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FileImportExportHelp;
import com.xbongbong.paas.help.ImportRedisHelper;
import com.xbongbong.paas.help.OssHelper;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.manager.feign.WorkOrderImportClient;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasProcessRelatedDataModel;
import com.xbongbong.paas.model.impl.PaasMenuModelImpl;
import com.xbongbong.paas.pojo.ErrorExcelDataPojo;
import com.xbongbong.paas.pojo.ErrorExcelDataPojoExt;
import com.xbongbong.paas.pojo.ExcelImportExtraPoJo;
import com.xbongbong.paas.pojo.ExportStatusPojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.ImportStatusPojo;
import com.xbongbong.paas.pojo.UniqueIndexPojo;
import com.xbongbong.paas.pojo.dto.ExcelExplainGetDTO;
import com.xbongbong.paas.pojo.dto.ExcelTemplateDTO;
import com.xbongbong.paas.pojo.dto.ExportFormatValueDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.ImportOtherParamsDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.CoverExcelDataPojo;
import com.xbongbong.paas.pojo.imports.MergeRegionRangePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.ExportFormDataVO;
import com.xbongbong.paas.pojo.vo.ExportFormatValueVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.FormDataRepeatVO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.ExcelImportService;
import com.xbongbong.paas.service.HandleImportService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PromotionActivityService;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.service.stage.StageHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.MD5Util;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExcelUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.businessdata.pojo.dto.BusinessDataDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.RegExConstant;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.ImportEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.QuotationErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.LinkFormItemDTO;
import com.xbongbong.pro.formexplain.pojo.vo.LinkFormItemVO;
import com.xbongbong.pro.message.enums.PushTypeEnum;
import com.xbongbong.pro.message.pojo.PushRefTypePojo;
import com.xbongbong.pro.message.pojo.dto.AutoClueAssignmentRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.MessageRabbitMqDTO;
import com.xbongbong.pro.message.pojo.dto.PublicGroupRabbitMqDTO;
import com.xbongbong.pro.oriStock.pojo.OriStockSaveDTO;
import com.xbongbong.pro.rabbitmq.producer.AutoClueAssignmentProducer;
import com.xbongbong.pro.rabbitmq.producer.BaseProducer;
import com.xbongbong.pro.rabbitmq.producer.PublicGroupProducer;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.pro.warehouse.pojo.dto.WarehouseListDTO;
import com.xbongbong.pro.warehouse.pojo.vo.WarehouseListVO;
import com.xbongbong.pro.webimport.LinkFormImportPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.export.ImportConstant;
import com.xbongbong.saas.domain.entity.CabinetFileEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.DistributorAreaEntity;
import com.xbongbong.saas.domain.entity.KnowledgeBaseEntity;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.enums.BirthdayTypeEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.GainPublicErrcodeEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.LinkAddOperationFlagEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.SubOptionTableHeadEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.base.ManagementBaseEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BatchFlowBillEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.CreditFixedLimitEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.KnowledgeDataEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OrderOutStockEnum;
import com.xbongbong.saas.enums.business.OriStockEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentDistributorEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetDistributorEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.PaymentTaskEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductSerialBalanceEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PromotionActivityManagementEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInstockEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.ReceiptOrderEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.ServiceProjectEnum;
import com.xbongbong.saas.enums.business.StockFlowBillEnum;
import com.xbongbong.saas.enums.business.StockProductEnum;
import com.xbongbong.saas.enums.business.StockStandingBookEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WaitOutstockEnum;
import com.xbongbong.saas.enums.business.WaitPurchaseProductEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.WarehouseOriStockEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.enums.product.PriceSetEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.SaasDetailPermissionHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ScoreRuleHelp;
import com.xbongbong.saas.help.workorder.WorkOrderV2ImportHelp;
import com.xbongbong.saas.model.CabinetFileModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.DistributorAreaModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.KnowledgeBaseModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.ProductCategoryModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.service.AssembleService;
import com.xbongbong.saas.service.BomBillService;
import com.xbongbong.saas.service.ClueService;
import com.xbongbong.saas.service.CompetitorService;
import com.xbongbong.saas.service.ContactService;
import com.xbongbong.saas.service.ContractService;
import com.xbongbong.saas.service.CostAdjustService;
import com.xbongbong.saas.service.CreditFixedLimitService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.CreditTemporaryLimitService;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.service.DistributorAccountService;
import com.xbongbong.saas.service.DistributorManageService;
import com.xbongbong.saas.service.FundTransferService;
import com.xbongbong.saas.service.InstockService;
import com.xbongbong.saas.service.InventoryService;
import com.xbongbong.saas.service.InvoiceService;
import com.xbongbong.saas.service.KnowledgeDataService;
import com.xbongbong.saas.service.MarketActivityService;
import com.xbongbong.saas.service.OpportunityService;
import com.xbongbong.saas.service.OrderService;
import com.xbongbong.saas.service.OriStockService;
import com.xbongbong.saas.service.OtherExpenseService;
import com.xbongbong.saas.service.OtherIncomeService;
import com.xbongbong.saas.service.OutstockService;
import com.xbongbong.saas.service.PayPlanService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.service.PriceSetService;
import com.xbongbong.saas.service.ProductSerialService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.ProductionOrderService;
import com.xbongbong.saas.service.PurchaseInvoiceService;
import com.xbongbong.saas.service.PurchaseService;
import com.xbongbong.saas.service.QuotationService;
import com.xbongbong.saas.service.RefundService;
import com.xbongbong.saas.service.ReturnedPurchaseService;
import com.xbongbong.saas.service.SupplierCommunicateService;
import com.xbongbong.saas.service.SupplierContactService;
import com.xbongbong.saas.service.SupplierService;
import com.xbongbong.saas.service.TransferService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WarehouseService;
import com.xbongbong.saas.service.WorkOrderService;
import com.xbongbong.saas.service.impl.SaasListServiceImpl;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.util.FundUtil;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.UserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 导入时一些逻辑处理Service层
 *
 * @author wufeng
 * @date 2018/9/25 10:14
 */
@Service("handleImportService")
public class HandleImportServiceImpl implements HandleImportService {

    private static final Logger LOG = LoggerFactory.getLogger(HandleImportServiceImpl.class);

    @Resource
    private ImportHelper importHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private SupplierService supplierService;
    @Resource
    private ContactService contactService;
    @Resource
    private ContractService contractService;
    @Resource
    private OrderService orderService;
    @Resource
    private BomBillService bomBillService;
    @Resource
    private ProductionOrderService productionOrderService;
    @Resource
    private SupplierContactService supplierContactService;
    @Resource
    private InstockService instockService;
    @Resource
    private OutstockService outstockService;
    @Resource
    private ProductService productService;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private SupplierCommunicateService supplierCommunicateService;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private ProductCategoryModel productCategoryModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private CustomerService customerService;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private OpportunityService opportunityService;
    @Resource
    private AssembleService assembleService;
    @Resource
    private ReturnedPurchaseService returnedPurchaseService;
    @Resource
    private PurchaseService purchaseService;
    @Resource
    private InventoryService inventoryService;
    @Resource
    private TransferService transferService;
    @Resource
    private InvoiceService invoiceService;
    @Resource
    private RefundService refundService;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private BaseProducer baseProducer;
    @Resource
    private EsHelper esHelper;
    @Resource
    private StageHandleFactory stageHandleFactory;
    @Resource
    private OssHelper ossHelper;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private UserModel userModel;
    @Resource
    private SaasDetailPermissionHelp saasDetailPermissionHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private ExcelImportService excelImportService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private OriStockService oriStockService;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private ImportRedisHelper importRedisHelper;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private PayPlanService payPlanService;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private PurchaseInvoiceService purchaseInvoiceService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ProductSerialService productSerialService;
    @Resource
    private ClueService clueService;
    @Resource
    private MarketActivityService marketActivityService;
    @Resource
    private LabelModel labelModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaasProcessRelatedDataModel paasProcessRelatedDataModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private PriceSetService priceSetService;
    @Resource
    private PromotionActivityService promotionActivityService;
    @Resource
    private ScoreRuleHelp scoreRuleHelp;
    @Resource
    private AutoClueAssignmentProducer autoClueAssignmentProducer;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private CreditTemporaryLimitService creditTemporaryLimitService;
    @Resource
    private CreditFixedLimitService creditFixedLimitService;
    @Resource
    private DistributorAreaModel distributorAreaModel;
    @Resource
    private DistributorManageService distributorManageService;
    @Resource
    private DistributorAccountService distributorAccountService;
    @Resource
    private FundTransferService fundTransferService;
    @Resource
    private OtherIncomeService otherIncomeService;
    @Resource
    private OtherExpenseService otherExpenseService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private SaasListServiceImpl saasListService;
    @Resource
    private CostAdjustService costAdjustService;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private PublicGroupProducer publicGroupProducer;
    @Resource
    private KnowledgeDataService knowledgeDataService;
    @Resource
    private KnowledgeBaseModel knowledgeBaseModel;
    @Resource
    private WorkOrderImportClient workOrderImportClient;
    @Resource
    private WorkOrderV2ImportHelp workOrderV2ImportHelp;
    @Resource
    private ExcelOperatorServiceImpl excelOperatorService;
    @Resource
    private PaasMenuModelImpl paasMenuModel;
    @Resource
    private CompetitorService competitorService;
    @Resource
    private FileImportExportHelp fileImportExportHelp;
    @Resource
    private CabinetFileModel cabinetFileModel;

    @Override
    public PaasFormDataEntity getPaasForm(ImportFormDataDTO importFormDataDTO) throws XbbException {
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        try {
            BeanUtil.copyProperties(importFormDataDTO, paasFormDataEntity);
            paasFormDataEntity.setOwnerId(importFormDataDTO.getUserId());

            paasFormDataEntity.setFlowStatus(FlowStatusEnum.APPROVAL_PENDING.getType());
            // 所属部门的id，由前端传入
            paasFormDataEntity.setDepartmentId(0L);
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(importFormDataDTO.getFormId(), importFormDataDTO.getCorpid());
            if (paasFormEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
            if (paasFormEntityExt.getIsProcessForm().equals(1)) {
                // TODO 流程逻辑
            }
            paasFormDataEntity.setCreatorId(importFormDataDTO.getUserId());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return paasFormDataEntity;
    }

    @Override
    public JSONArray handleSpecialExplain(List<FieldAttrEntityForImport> fieldAttrList, ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        Long formId = excelTemplateDTO.getFormId();
        String corpid = excelTemplateDTO.getCorpid();
        Integer businessType = excelTemplateDTO.getBusinessType();
        //Integer distributorMark = excelTemplateDTO.getDistributorMark();
        Integer distributorMark = Optional.ofNullable(excelTemplateDTO.getDistributorMark()).orElse(BasicConstant.ZERO);
        // 过滤新建时不需要展示的字段，根据showType来过滤
        List<Integer> showTypeList = ShowTypeEnum.getAddShowType();
        //查看是否启用多单位公司级配置
        CompanyConfigEntity configEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_MULTI_UNIT.getAlias(), corpid);
        //导出时，特殊处理字段的showType,不然会被过滤掉
        specialHandleShowType4Export(excelTemplateDTO.getFormImportOrExport(),businessType,fieldAttrList);
        //工单特殊处理，大部分都要显示不需要过滤，下面单独过滤
        List<Integer> noFilterList = Arrays.asList(XbbRefTypeEnum.WORK_ORDER.getCode(), XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode(),
                XbbRefTypeEnum.WAIT_PURCHASE.getCode(), XbbRefTypeEnum.WORK_ORDER_V2.getCode(), XbbRefTypeEnum.RECEIPT_ORDER.getCode());
        if (!noFilterList.contains(businessType)) {
            fieldAttrList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getIsRedundant(), 0) && !showTypeList.contains(fieldAttrEntity.getShowType()) && !(Objects.equals(excelTemplateDTO.getFormImportOrExport(),2) && Objects.equals("extensionField",fieldAttrEntity.getSaasAttr())) );
        }
        List<FieldAttrEntityForImport> subFieldAttrList = new ArrayList<>();
        //有资金账户的业务
        boolean fundAccountFlag = Arrays.asList(XbbRefTypeEnum.PAY_SHEET.getCode(), XbbRefTypeEnum.PAYMENT_SHEET.getCode(), XbbRefTypeEnum.OTHER_INCOME.getCode(), XbbRefTypeEnum.OTHER_EXPENSE.getCode(), XbbRefTypeEnum.FUND_TRANSFER.getCode()).contains(businessType);
        //资金账户对应saasAttr
        List<String> fundAccountSaasAttrList = FundUtil.getFundAccountSaasAttrList();
        fieldAttrList.forEach(fieldAttrEntityForImport -> {
            if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                subFieldAttrList.add(fieldAttrEntityForImport);
            }
            if(Objects.nonNull(configEntity)
                    && Objects.equals(BasicConstant.ONE, Integer.valueOf(configEntity.getConfigValue()))
                    && Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())
                    && StockConstant.EXPORT_MULTI_UNIT_TYPE_LIST.contains(businessType)
                    && !Objects.equals(excelTemplateDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())
                    && !Objects.equals(excelTemplateDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PURCHASE.getCode())
                    && !Objects.equals(excelTemplateDTO.getSubBusinessType(),XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())
                    && !Objects.equals(excelTemplateDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())){
                importHelper.exportAddExplain((List<FieldAttrEntity>) fieldAttrEntityForImport.getSubForm().getItems(), new ArrayList<>());
            }
            if (fundAccountFlag && fundAccountSaasAttrList.contains(fieldAttrEntityForImport.getSaasAttr())) {
                List<ItemPoJo> fundAccounts = proFormHelp.handleFundAccountItems(corpid, businessType);
                fundAccounts.removeIf(account -> Objects.equals(account.getShowType(), ShowTypeEnum.EXCLUDE_NEW.getCode()));
                fieldAttrEntityForImport.setItems(fundAccounts);
            }
        });
        for (FieldAttrEntityForImport fieldAttrEntityForImport : subFieldAttrList) {
            SubFormPoJo subFormPoJo = fieldAttrEntityForImport.getSubForm();
            List<? extends FieldAttrEntity> fieldAttrEntityForImportList = subFormPoJo.getItems();
            fieldAttrEntityForImportList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getIsRedundant(), 0) && !showTypeList.contains(fieldAttrEntity.getShowType()));
            subFormPoJo.setItems(fieldAttrEntityForImportList);
            fieldAttrEntityForImport.setSubForm(subFormPoJo);
        }
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(businessType, distributorMark));
        boolean isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);

        WarehouseListDTO warehouseListDTO = new WarehouseListDTO();
        BeanUtil.copyProperties(excelTemplateDTO, warehouseListDTO);
        WarehouseListVO warehouseListVO = warehouseService.getManagetWarehouses(warehouseListDTO);
        List<String> productEnumList = RelativeProductImportEnum.getByBusinessType(businessType, excelTemplateDTO.getFormImportOrExport());
        if (Objects.nonNull(productEnumList)) {
            PaasFormExplainEntity paasFormProductExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(paasFormProductExplainEntity.getExplains(), null);
            List<String> needUpdateAttrs = Arrays.asList(SelectProductEnum.COST.getAttr(), SelectProductEnum.PRICE.getAttr());
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())) {
                    fieldAttrEntityForImport.setNeedImportSeparately(ImportConstant.NEED_IMPORT_SEPARATELY);
                    if (Objects.equals(businessType, XbbRefTypeEnum.ASSEMBLE.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), AssembleEnum.IN_PRODUCTS.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 1)) {
                            productEnumList = RelativeProductImportEnum.IMPORT_ASSEMBLE_IN_PRODUCT.getProductEnumList();
                        } else {
                            productEnumList = RelativeProductImportEnum.EXPORT_ASSEMBLE_IN_PRODUCT.getProductEnumList();
                        }
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.ASSEMBLE.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), AssembleEnum.OUT_PRODUCTS.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 1)) {
                            productEnumList = RelativeProductImportEnum.IMPORT_ASSEMBLE_OUT_PRODUCT.getProductEnumList();
                        } else {
                            productEnumList = RelativeProductImportEnum.EXPORT_ASSEMBLE_OUT_PRODUCT.getProductEnumList();
                        }
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.BOM_BILL.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), BomBillEnum.MATERIEL.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 1)) {
                            productEnumList = RelativeProductImportEnum.IMPORT_BOM_MATERIAL_PRODUCT.getProductEnumList();
                        } else {
                            productEnumList = RelativeProductImportEnum.EXPORT_BOM_MATERIAL_PRODUCT.getProductEnumList();
                        }
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.BOM_BILL.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), BomBillEnum.PRODUCT.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 1)) {
                            productEnumList = RelativeProductImportEnum.IMPORT_BOM_FINISH_PRODUCT.getProductEnumList();
                        } else {
                            productEnumList = RelativeProductImportEnum.EXPORT_BOM_FINISH_PRODUCT.getProductEnumList();
                        }
                        fieldAttrEntityForImport.setNeedImportSeparately(0);
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), ProductionOrderEnum.MATERIEL.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 1)) {
                            productEnumList = RelativeProductImportEnum.IMPORT_PRODUCTION_ORDER_MATERIAL_PRODUCT.getProductEnumList();
                        } else {
                            productEnumList = RelativeProductImportEnum.EXPORT_PRODUCTION_ORDER_MATERIAL_PRODUCT.getProductEnumList();
                        }
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), ProductionOrderEnum.PRODUCT.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 1)) {
                            productEnumList = RelativeProductImportEnum.IMPORT_PRODUCTION_ORDER_FINISH_PRODUCT.getProductEnumList();
                        } else {
                            productEnumList = RelativeProductImportEnum.EXPORT_PRODUCTION_ORDER_FINISH_PRODUCT.getProductEnumList();
                        }
                        fieldAttrEntityForImport.setNeedImportSeparately(0);
                    }else if (Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode()) && Objects.equals(fieldAttrEntityForImport.getAttr(), PromotionActivityManagementEnum.APPLICABLE_PRODUCT.getAttr())) {
                        if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), 2)) {
                            productEnumList = RelativeProductImportEnum.EXPORT_PROMOTION_ACTIVITY_MANAGEMENT_PRODUCT.getProductEnumList();
                        }
                    }
                    List<FieldAttrEntityForImport> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems()), FieldAttrEntityForImport.class);
                    List<FieldAttrEntityForImport> basicProductList = new ArrayList<>();
                    int productIndex = 0;
                    for (int i = subExplainList.size() - 1; i >= 0; i --) {
                        FieldAttrEntityForImport subAttr = subExplainList.get(i);
                        if (Objects.equals(subAttr.getAttr(), SelectProductEnum.PRODUCT.getAttr())) {
                            List<SelectProductEnum> selectProductEnumList = Arrays.asList(SelectProductEnum.PRODUCT_NAME,SelectProductEnum.PRODUCT_NO,SelectProductEnum.SPECIFICATION,SelectProductEnum.BARCODE);
                            List<LinkedAttrPoJo> linkedAttrPoJos = subAttr.getLinkInfo().getLinkedShowAttr();
                            Map<String, String> nameMap = new HashMap<>(linkedAttrPoJos.size());
                            linkedAttrPoJos.forEach(item -> nameMap.put(item.getAttr(), item.getAttrName()));
                            selectProductEnumList.forEach(item -> {
                                FieldAttrEntityForImport forImport = new FieldAttrEntityForImport();
                                forImport.setIsRedundant(0);
                                BeanUtil.copyProperties(item, forImport);
                                if (Objects.equals(item, SelectProductEnum.PRODUCT_NO)) {
                                    if (nameMap.containsKey(ProductEnum.SERIALNO.getAttr())) {
                                        forImport.setAttrName(nameMap.get(ProductEnum.SERIALNO.getAttr()));
                                    }
                                    forImport.setRequired(1);
                                } else if (Objects.equals(item, SelectProductEnum.PRODUCT_NAME)) {
                                    forImport.setAttrName(subAttr.getAttrName());
                                } else if (Objects.equals(item, SelectProductEnum.SPECIFICATION) && nameMap.containsKey(ProductEnum.SPECIFICATION.getAttr())) {
                                    forImport.setAttrName(nameMap.get(ProductEnum.SPECIFICATION.getAttr()));
                                }else if (Objects.equals(item, SelectProductEnum.BARCODE) && nameMap.containsKey(ProductEnum.BARCODE.getAttr())) {
                                    forImport.setAttrName(nameMap.get(ProductEnum.BARCODE.getAttr()));
                                }
                                basicProductList.add(forImport);
                            });
                            productIndex = i;
                            subExplainList.remove(i);
                        } else if (Objects.equals(subAttr.getAttr(), SelectProductEnum.WAREHOUSE.getAttr()) && Objects.equals(subAttr.getIsRedundant(), 0)) {
                            // 采购退货不应该有仓库字段
                            if (Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode())) {
                                subExplainList.remove(i);
                            } else {
                                setWareHouseToCombo(subAttr, warehouseListVO);
                            }
                        } else if (Objects.equals(subAttr.getAttr(), SelectProductEnum.DISCOUNT.getAttr()) && Objects.equals(subAttr.getIsRedundant(), 0)) {
                            subAttr.setRequired(0);
                        } else if (Objects.equals(SelectProductEnum.UNIT.getAttr(), subAttr.getAttr())) {
                            subAttr.setFieldType(FieldTypeEnum.TEXT.getType());
                        } else if (productEnumList.contains(subAttr.getAttr())) {
                            if (needUpdateAttrs.contains(subAttr.getAttr()) && productExplainMap.containsKey(subAttr.getAttr())) {
                                subAttr.setVisible((productExplainMap.get(subAttr.getAttr()).getVisible()));
                                subAttr.setVisibleScopeRule(productExplainMap.get(subAttr.getAttr()).getVisibleScopeRule());
                                subAttr.setVisibleScopeEnable(productExplainMap.get(subAttr.getAttr()).getVisibleScopeEnable());
                                subAttr.setAccuracy(productExplainMap.get(subAttr.getAttr()).getAccuracy());
                            }
                        } else {
                            if (!Objects.equals(subAttr.getIsRedundant(), 1)) {
                                subExplainList.remove(i);
                            } else {
                                // 产品子表单中地址和定位解析
                                List<ImportEnum> fieldList;
                                if (Objects.equals(subAttr.getFieldType(), FieldTypeEnum.ADDRESS.getType())) {
                                    Integer showDetailAddress = subAttr.getShowDetailAddress();
                                    if (Objects.equals(showDetailAddress, 1)) {
                                        fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA, ImportEnum.DETAIL_ADDRESS);
                                    } else {
                                        fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA);
                                    }
                                    setSpecialFields2SubForm(subAttr, fieldList);
                                } else if (Objects.equals(subAttr.getFieldType(), FieldTypeEnum.LOCATION.getType())) {
                                    fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA, ImportEnum.DETAIL_ADDRESS);
                                    setSpecialFields2SubForm(subAttr, fieldList);
                                }
                            }
                        }
                    }

                    if (CollectionsUtil.isNotEmpty(basicProductList)) {
                        if (productIndex > subExplainList.size()) {
                            subExplainList.addAll(basicProductList);
                        } else {
                            subExplainList.addAll(productIndex, basicProductList);
                        }
                    }
                    SubFormPoJo subFormPoJo = new SubFormPoJo();
                    subFormPoJo.setItems(subExplainList);
                    fieldAttrEntityForImport.setSubForm(subFormPoJo);
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.SUB_FORM.getType());
                }
                if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.SELECT_SERVICE.getType())) {
                    List<FieldAttrEntityForImport> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems()), FieldAttrEntityForImport.class);
                    List<FieldAttrEntityForImport> basicServiceList = new ArrayList<>();
                    int productIndex = 0;
                    for (int i = subExplainList.size() - 1; i >= 0; i--) {
                        FieldAttrEntityForImport subAttr = subExplainList.get(i);
                        if (Objects.equals(subAttr.getAttr(), ServiceProjectEnum.NAME.getAttr())) {
                            List<ServiceProjectEnum> serviceProjectEnumList = Arrays.asList(ServiceProjectEnum.NAME, ServiceProjectEnum.SERIALNO);
                            List<LinkedAttrPoJo> linkedAttrPoJos = subAttr.getLinkInfo().getLinkedShowAttr();
                            Map<String, String> nameMap = new HashMap<>(linkedAttrPoJos.size());
                            linkedAttrPoJos.forEach(item -> nameMap.put(item.getAttr(), item.getAttrName()));
                            serviceProjectEnumList.forEach(item -> {
                                FieldAttrEntityForImport forImport = new FieldAttrEntityForImport();
                                forImport.setIsRedundant(0);
                                BeanUtil.copyProperties(item, forImport);
                                if (Objects.equals(item, ServiceProjectEnum.NAME)) {
                                    forImport.setAttrName(subAttr.getAttrName());
                                } else if (Objects.equals(item, ServiceProjectEnum.SERIALNO) && nameMap.containsKey(ServiceProjectEnum.SERIALNO.getAttr())) {
                                    forImport.setAttrName(nameMap.get(ServiceProjectEnum.SERIALNO.getAttr()));
                                }
                                basicServiceList.add(forImport);
                            });
                            productIndex = i;
                            subExplainList.remove(i);
                        } else if (Objects.equals(ServiceProjectEnum.UNIT.getAttr(), subAttr.getAttr())) {
                            subAttr.setFieldType(FieldTypeEnum.TEXT.getType());
                        } else if (Objects.equals(ShowTypeEnum.NONE.getCode(), subAttr.getShowType())) {
                            subExplainList.remove(i);
                        } else {
                            // 子表单中地址和定位解析
                            List<ImportEnum> fieldList;
                            if (Objects.equals(subAttr.getFieldType(), FieldTypeEnum.ADDRESS.getType())) {
                                Integer showDetailAddress = subAttr.getShowDetailAddress();
                                if (Objects.equals(showDetailAddress, 1)) {
                                    fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA, ImportEnum.DETAIL_ADDRESS);
                                } else {
                                    fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA);
                                }
                                setSpecialFields2SubForm(subAttr, fieldList);
                            } else if (Objects.equals(subAttr.getFieldType(), FieldTypeEnum.LOCATION.getType())) {
                                fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA, ImportEnum.DETAIL_ADDRESS);
                                setSpecialFields2SubForm(subAttr, fieldList);
                            }
                        }
                    }

                    if (CollectionsUtil.isNotEmpty(basicServiceList)) {
                        if (productIndex > subExplainList.size()) {
                            subExplainList.addAll(basicServiceList);
                        } else {
                            subExplainList.addAll(productIndex, basicServiceList);
                        }
                    }
                    SubFormPoJo subFormPoJo = new SubFormPoJo();
                    subFormPoJo.setItems(subExplainList);
                    fieldAttrEntityForImport.setSubForm(subFormPoJo);
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.SUB_FORM.getType());

                }
            }
        }
        boolean isStock = Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.STOCK_SEARCH.getCode()) || Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode()) || Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode());
        fieldAttrList.removeIf(fieldAttrEntityForImport -> isStock && (Objects.equals(fieldAttrEntityForImport.getAttr(), ProductEnum.VISBLE_DEPT.getAttr()) || Objects.equals(fieldAttrEntityForImport.getAttr(), ProductEnum.VISBLE_USER.getAttr())));


        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getSaasAttr(), CustomerManagementEnum.TYPE.getSaasAttr())) {
                        fieldAttrEntity.setItems(dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STATUS,corpid,null));
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.IS_ARCHIVED.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        List<ItemPoJo> itemPoJoList = new ArrayList<>();
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setText(I18nMessageUtil.getMessage(CommonConstant.NO));
                        itemPoJo.setValue(ArchivedEnum.UN_ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo);
                        ItemPoJo itemPoJo1 = new ItemPoJo();
                        itemPoJo1.setText(I18nMessageUtil.getMessage(CommonConstant.YES));
                        itemPoJo1.setValue(ArchivedEnum.ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo1);
                        fieldAttrEntity.setItems(itemPoJoList);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.WASTAGE.getAttr())) {
                        fieldAttrEntity.setItems(dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STAGE_WASTAGE, corpid, formId));
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.CUSTOMER_STAGE.getAttr())){
                        //导入客户阶段id需要字符串类型
                        StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                        List<ItemPoJo> itemList = stageHandle.getItemListForImport(corpid, formId, BasicConstant.ONE, fieldAttrEntity);
                        if (CollectionsUtil.isNotEmpty(itemList)) {
                            itemList.forEach(itemPoJo -> itemPoJo.setValue(String.valueOf(itemPoJo.getValue())));
                            fieldAttrEntity.setItems(itemList);
                        }
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.CREATOR.getAttr())) {
                        fieldAttrEntity.setRequired(0);
                    }
                }
                // 顺序不可调换，否则会有大问题
                if (isImport) {
                    fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), CustomerManagementEnum.WASTAGE.getAttr())
                            || Objects.equals(field.getAttr(), CustomerManagementEnum.WASTAGE_MEMO.getAttr())
                            || Objects.equals(field.getAttr(), CustomerManagementEnum.LAST_CONNECT_TIME.getAttr())
                            || Objects.equals(field.getAttr(), CustomerManagementEnum.CREATOR_ID.getAttr()));
                }
                // 公海客户支持导出前负责人
                if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT) && Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())) {
                    FieldAttrEntityForImport preField = new FieldAttrEntityForImport();
                    preField.setAttr("preOwnerId");
                    preField.setRequired(0);
                    preField.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                    preField.setFieldType(FieldTypeEnum.USER_GROUP.getType());
                    fieldAttrList.add(0, preField);
                }
                break;
            case CLUE:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.IS_ARCHIVED.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        List<ItemPoJo> itemPoJoList = new ArrayList<>();
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setText(I18nMessageUtil.getMessage(CommonConstant.NO));
                        itemPoJo.setValue(ArchivedEnum.UN_ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo);
                        ItemPoJo itemPoJo1 = new ItemPoJo();
                        itemPoJo1.setText(I18nMessageUtil.getMessage(CommonConstant.YES));
                        itemPoJo1.setValue(ArchivedEnum.ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo1);
                        fieldAttrEntity.setItems(itemPoJoList);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.INVALID_REASON.getAttr())) {
                        fieldAttrEntity.setItems(dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CLUE_STAGE_INVALID, corpid, formId));
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.CLUE_STAGE.getAttr())){
                        StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CLUE.getCode());
                        fieldAttrEntity.setItems(stageHandle.getItemListForImport(corpid, formId, BasicConstant.ONE, fieldAttrEntity));
                    }
                }
                // 顺序不可调换，否则会有大问题
                if (isImport) {
                    fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), ClueEnum.INVALID_REASON.getAttr())
                            || Objects.equals(field.getAttr(), ClueEnum.INVALID_MEMO.getAttr())
                            || Objects.equals(field.getAttr(), ClueEnum.LAST_CONNECT_TIME.getAttr())
                            || Objects.equals(field.getAttr(), ClueEnum.CREATOR_ID.getAttr()));
                }
                // 公海线索支持导出前负责人
                if (Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT) && Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
                    FieldAttrEntityForImport preField = new FieldAttrEntityForImport();
                    preField.setAttr("preOwnerId");
                    preField.setRequired(0);
                    preField.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                    preField.setFieldType(FieldTypeEnum.USER_GROUP.getType());
                    fieldAttrList.add(0, preField);
                }
                break;
            case SALES_OPPORTUNITY:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), SalesOpportunityEnum.WASTAGE.getAttr())) {
                        fieldAttrEntity.setItems(dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.SALE_STAGE_WASTAGE, corpid, formId));
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), SalesOpportunityEnum.SALE_STAGE.getAttr())){
                        StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                        fieldAttrEntity.setItems(stageHandle.getItemListForImport(corpid, formId, BasicConstant.ONE, fieldAttrEntity));
                    }
                }
                if (isImport) {
                    fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), SalesOpportunityEnum.WASTAGE.getAttr())
                            || Objects.equals(field.getAttr(), SalesOpportunityEnum.WASTAGE_MEMO.getAttr())
                            || Objects.equals(field.getAttr(), SalesOpportunityEnum.COST.getAttr())
                            || Objects.equals(field.getAttr(), SalesOpportunityEnum.GROSS_PROFIT.getAttr())
                            || Objects.equals(field.getAttr(), SalesOpportunityEnum.GROSS_PROFIT_RATE.getAttr())
                            || Objects.equals(field.getAttr(), SalesOpportunityEnum.LAST_CONNECT_TIME.getAttr()));
                }
                break;
            case CONTRACT:
                for (int i = 0; i< fieldAttrList.size(); i ++) {
                    FieldAttrEntityForImport fieldAttrEntity = fieldAttrList.get(i);
                    if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.STATUS.getAttr())) {
                        List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CONTRACT_STATUS,corpid,null);
                        fieldAttrEntity.setItems(itemPoJoList);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.EXPRESS_NAME.getAttr())) {
                        List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.EXPRESS_NAME,corpid,null);
                        fieldAttrEntity.setItems(itemPoJoList);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.ARCHIVED.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        List<ItemPoJo> itemPoJoList = new ArrayList<>();
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setText(I18nMessageUtil.getMessage(CommonConstant.NO));
                        itemPoJo.setValue(ArchivedEnum.UN_ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo);
                        ItemPoJo itemPoJo1 = new ItemPoJo();
                        itemPoJo1.setText(I18nMessageUtil.getMessage(CommonConstant.YES));
                        itemPoJo1.setValue(ArchivedEnum.ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo1);
                        fieldAttrEntity.setItems(itemPoJoList);
                    }
                    if (isImport) {
                        fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), ContractEnum.CONTRACT_COST.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.CASH_PROFIT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.CASH_PROFIT_RATE.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.GROSS_PROFIT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.GROSS_PROFIT_RATE.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.FINISH_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.BAD_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.UN_FINISH_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.PAY_PERCENT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.INVOICE_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), ContractEnum.UN_INVOICE_AMOUNT.getAttr())
                        );
                    }
                }
                break;
            case ORDER:
                for (int i = 0; i< fieldAttrList.size(); i ++) {
                    FieldAttrEntityForImport fieldAttrEntity = fieldAttrList.get(i);
                    if (Objects.equals(fieldAttrEntity.getAttr(), OrderEnum.ARCHIVED.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        List<ItemPoJo> itemPoJoList = new ArrayList<>();
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setText(I18nMessageUtil.getMessage(CommonConstant.NO));
                        itemPoJo.setValue(ArchivedEnum.UN_ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo);
                        ItemPoJo itemPoJo1 = new ItemPoJo();
                        itemPoJo1.setText(I18nMessageUtil.getMessage(CommonConstant.YES));
                        itemPoJo1.setValue(ArchivedEnum.ARCHIVED.getCode());
                        itemPoJoList.add(itemPoJo1);
                        fieldAttrEntity.setItems(itemPoJoList);
                    }
                    if (isImport) {
                        fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), OrderEnum.ORDER_COST.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.CASH_PROFIT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.CASH_PROFIT_RATE.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.GROSS_PROFIT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.GROSS_PROFIT_RATE.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.FINISH_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.BAD_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.UN_FINISH_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.PAY_PERCENT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.INVOICE_AMOUNT.getAttr())
                                || Objects.equals(field.getAttr(), OrderEnum.UN_INVOICE_AMOUNT.getAttr())
                        );
                    }
                }
                break;
            case CUSTOMER_COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                fieldAttrList.removeIf(field -> Objects.equals(field.getAttr(), CustomerCommunicateEnum.IF_REMIND.getAttr())
                || Objects.equals(field.getAttr(), CustomerCommunicateEnum.NEXT_COMMUNICATE_TIME.getAttr())
                || Objects.equals(field.getAttr(), CustomerCommunicateEnum.NOTIFY_TYPE.getAttr())
                || Objects.equals(field.getAttr(), CustomerCommunicateEnum.NOTIFY_TIME.getAttr())
                || Objects.equals(field.getAttr(), CustomerCommunicateEnum.ENTER_COMMUNICATE_PLAN.getAttr())
                || Objects.equals(field.getAttr(), CustomerCommunicateEnum.NEXT_NOTIFY_MEMO.getAttr()));
                handleCommunicateBusiness(fieldAttrList, corpid);
                break;
            case SUPPLIER_COMMUNICATE:
                handleCommunicateBusiness(fieldAttrList, corpid);
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), SupplierCommunicateEnum.SUPPLIER_ID.getAttr())) {
                        setSupplierToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case PURCHASE_INSTOCK:
            case OTHER_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case REFUND_INSTOCK:
            case PRODUCTION_INSTOCK:
                List<Integer> instockType;
                if (isImport) {
                    instockType = Collections.singletonList(InstockTypeEnum.OTHER_INSTOCK.getCode());
                } else {
                    instockType = Arrays.asList(InstockTypeEnum.OTHER_INSTOCK.getCode(), InstockTypeEnum.TRANSFER_INSTOCK.getCode(), InstockTypeEnum.INVENTORY_INSTOCK.getCode(),InstockTypeEnum.ASSEMBLE_INSTOCK.getCode());
                }
                Iterator<FieldAttrEntityForImport> it = fieldAttrList.iterator();
                while (it.hasNext()) {
                    FieldAttrEntityForImport fieldAttrEntity = it.next();
                    if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.WAREHOUSE_ID.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setWareHouseToCombo(fieldAttrEntity, warehouseListVO);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.TYPE.getAttr())) {
                        fieldAttrEntity.getItems().removeIf(itemPoJo -> !instockType.contains(Integer.valueOf(itemPoJo.getValue().toString())));
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.REF_ID.getAttr()) && Objects.equals(xbbRefTypeEnum.getCode(), XbbRefTypeEnum.OTHER_INSTOCK.getCode()) && isImport) {
                        // 其他入库不用填关联单据，必填校验会出问题
                        it.remove();;
                    }
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case ORDER_OUTSTOCK:
                List<Integer> outstockType;
                if (isImport) {
                    outstockType = Arrays.asList(OutstockTypeEnum.OTHER_OUTSTOCK.getCode());
                } else {
                    outstockType = Arrays.asList(OutstockTypeEnum.OTHER_OUTSTOCK.getCode(), OutstockTypeEnum.TRANSFER_OUTSTOCK.getCode(), OutstockTypeEnum.INVENTORY_OUTSTOCK.getCode(),OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode());
                }
                Iterator<FieldAttrEntityForImport> outStockIt = fieldAttrList.iterator();
                while (outStockIt.hasNext()) {
                    FieldAttrEntityForImport fieldAttrEntity = outStockIt.next();
                    if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.WAREHOUSE_ID.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setWareHouseToCombo(fieldAttrEntity, warehouseListVO);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.REF_ID.getAttr()) && Objects.equals(xbbRefTypeEnum.getCode(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) && isImport) {
                        // 其他入库不用填关联单据，必填校验会出问题
                        outStockIt.remove();
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.EXPRESS_NAME.getAttr())) {
                        List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.EXPRESS_NAME, corpid, excelTemplateDTO.getFormId());
                        fieldAttrEntity.setItems(itemPoJoList);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.TYPE.getAttr())) {
                        fieldAttrEntity.getItems().removeIf(itemPoJo -> !outstockType.contains(Integer.valueOf(itemPoJo.getValue().toString())));
                    }
                }
                break;
            case PRODUCT:
                Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                if (!isJxcUse) {
                    fieldAttrList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.WAREHOUSE.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.WAREHOUSE_INFO.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.STOCK_INFO.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.STOCK_NOTIFY.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.IS_NOTIFY.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.SUPPLIER.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.ASSOCIATED_INFO.getAttr()));
                }
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.CATEGORY_ID.getAttr())) {
                        setCategoryToCombo(fieldAttrEntity, excelTemplateDTO);
                    } else if (Objects.nonNull(configEntity) && Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.UNIT.getAttr()) && Objects.equals(BasicConstant.ONE, Integer.valueOf(configEntity.getConfigValue()))){
                        setUnitsToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                if (Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.STOCK_SEARCH.getCode())) {

                } else if (Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
                    FieldAttrEntityForImport stockAttr = null;
                    Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
                    while (iterator.hasNext()) {
                        FieldAttrEntityForImport forImport = iterator.next();
                        if (Objects.equals(forImport.getAttr(), ProductEnum.STOCK.getAttr())) {
                            stockAttr = forImport;
                            iterator.remove();
                        }
                    }
                    //fieldAttrList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.STOCK.getAttr()));
                    addWarningSearchAttr(fieldAttrList, stockAttr);
                } else if (Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    addGuaranteeSearchAttr(fieldAttrList);
                } else {
                    fieldAttrList.removeIf(field -> Objects.equals(field.getAttr(), ProductEnum.STOCK.getAttr())&&
                            Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT));
                }
                break;
            case ASSEMBLE:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), AssembleEnum.INTO_WAREHOUSE_ID.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), AssembleEnum.OUT_WAREHOUSE_ID.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setWareHouseToCombo(fieldAttrEntity, warehouseListVO);
                    }
                }
                break;
            case TRANSFER:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), TransferEnum.INTO_WAREHOUSE_ID.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), TransferEnum.OUT_WAREHOUSE_ID.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setWareHouseToCombo(fieldAttrEntity, warehouseListVO);
                    }
                }
                break;
            case INVENTORY:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), InventoryEnum.WAREHOUSE_ID.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setWareHouseToCombo(fieldAttrEntity, warehouseListVO);
                    }
                }
                break;
            case PRODUCTION_ORDER:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setWareHouseToCombo(fieldAttrEntity, warehouseListVO);
                    }
                }
                break;
            case WORK_REPORT:
                Integer subBusinessType = excelTemplateDTO.getSubBusinessType();
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), WorkReportFieldEnum.THIS_STATISTIC.getAttr())) {
                        handleWorkReportStatisticDataExplain(subBusinessType, fieldAttrEntity);
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), WorkReportFieldEnum.THIS_PLAN.getAttr())) {
                        List<FieldAttrEntity> planFieldList = new ArrayList<>();
                        FieldAttrEntity statusField = new FieldAttrEntity();
                        statusField.setAttr("text_2");
                        statusField.setAttrName(I18nMessageUtil.getMessage(CommonConstant.STATUS));
                        statusField.setFieldType(FieldTypeEnum.SWITCH.getType());
                        planFieldList.add(statusField);
                        FieldAttrEntity contentField = new FieldAttrEntity();
                        contentField.setAttr("text_1");
                        contentField.setAttrName(I18nMessageUtil.getMessage(CommonConstant.PLAN));
                        planFieldList.add(contentField);
                        setSpecialFields2SubForm(fieldAttrEntity, planFieldList);
                        fieldAttrEntity.setNeedImportSeparately(ImportConstant.NEED_IMPORT_SEPARATELY);
                    }
                }
                break;
            case PAY_PLAN:
                fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(PayPlanEnum.ADD_PAYPLAN.getAttr(), fieldAttrEntityForImport.getAttr()));
                if (isImport) {
                    fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(PayPlanEnum.REAL_PAY_TIME.getAttr(), fieldAttrEntityForImport.getAttr())
                            || Objects.equals(PayPlanEnum.UN_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr())
                            || Objects.equals(PayPlanEnum.REAL_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr())
                            || Objects.equals(PayPlanEnum.BAD_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr())
                            || Objects.equals(PayPlanEnum.INVOICE_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr()));
                }
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), PayPlanEnum.LINK_SUPPLIER.getAttr())) {
                        setSupplierToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case PAY_SHEET:
                // 关联供应商处理成下拉框形式
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), PaySheetEnum.LINK_SUPPLIER.getAttr())) {
                        setSupplierToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case PAYMENT:
                fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(PaymentEnum.ADD_PAYMENT.getAttr(), fieldAttrEntityForImport.getAttr()));
                if (isImport) {
                    fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(PaymentEnum.REAL_PAY_TIME.getAttr(), fieldAttrEntityForImport.getAttr())
                    || Objects.equals(PaymentEnum.UN_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr())
                    || Objects.equals(PaymentEnum.REAL_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr())
                    || Objects.equals(PaymentEnum.BAD_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr())
                    || Objects.equals(PaymentEnum.INVOICE_AMOUNT.getAttr(), fieldAttrEntityForImport.getAttr()));
                }
                break;
            case WORK_ORDER:
                fieldAttrList.removeIf(fieldAttrEntityForImport ->
                        (Objects.equals(fieldAttrEntityForImport.getAttr(), WorkOrderEnum.MANAGER_ID.getAttr()) ||Objects.equals(fieldAttrEntityForImport.getAttr(), WorkOrderEnum.LINK_CUSTOMER_HIDE.getAttr()) || Objects.equals(fieldAttrEntityForImport.getAttr(), WorkOrderEnum.LINK_CONTACT_HIDE.getAttr()) || Objects.equals(fieldAttrEntityForImport.getAttr(), WorkOrderEnum.LINK_OPPORTUNITY_HIDE.getAttr()) || Objects.equals(fieldAttrEntityForImport.getAttr(), WorkOrderEnum.LINK_CONTRACT_HIDE.getAttr()))  && !(Objects.equals(excelTemplateDTO.getFormImportOrExport(),2) && Objects.equals("extensionField",fieldAttrEntityForImport.getSaasAttr())));
                break;
            case PURCHASE:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.SUPPLIER_ID.getAttr())) {
                        setSupplierToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case SUPPLIER_CONTACT:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), SupplierContactEnum.SUPPLIER_ID.getAttr())) {
                        setSupplierToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case QUOTATION:
                for (int i = 0; i< fieldAttrList.size(); i ++) {
                    if (isImport) {
                        fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), QuotationEnum.CUSTOMER_NAME.getAttr())
                                || Objects.equals(field.getAttr(), QuotationEnum.CONTACT_NAME.getAttr())
                                || Objects.equals(field.getAttr(), QuotationEnum.OPPORTUNITY_NAME.getAttr())
                                || Objects.equals(field.getAttr(), QuotationEnum.ESTIMATE_COST.getAttr())
                                || Objects.equals(field.getAttr(), QuotationEnum.GROSS_PROFIT.getAttr())
                                || Objects.equals(field.getAttr(), QuotationEnum.GROSS_PROFIT_RATE.getAttr())
                                || Objects.equals(field.getAttr(), QuotationEnum.QUOTATION_NAME.getAttr()));
                    }
                }
                FieldAttrEntityForImport last1 = new FieldAttrEntityForImport();
                FieldAttrEntityForImport last2 = new FieldAttrEntityForImport();
                LinkedList<FieldAttrEntityForImport> list = new LinkedList<>();
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    //重新排序组号和版本号
                    if (Objects.equals(fieldAttrEntity.getAttr(), QuotationEnum.GROUP_NUMBER.getAttr())) {
                        //导入模版变报价单组号*（必填）
                        fieldAttrEntity.setRequired(1);
                        last1 = fieldAttrEntity;
                    } else if (Objects.equals(fieldAttrEntity.getAttr(), QuotationEnum.VERSION.getAttr())) {
                        //导入模版变版本号*（必填）
                        fieldAttrEntity.setRequired(1);
                        last2 = fieldAttrEntity;
                    }
                }
                list.add(0,last1);
                list.add(1, last2);
                fieldAttrList.removeIf(field->Objects.equals(field.getAttr(), QuotationEnum.GROUP_NUMBER.getAttr())
                        || Objects.equals(field.getAttr(), QuotationEnum.VERSION.getAttr()));
                list.addAll(fieldAttrList);
                fieldAttrList = list;
                break;
            case REFUND:
                if (isImport) {
                    fieldAttrList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.INVOICES.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.PAYMENT_SHEETS.getAttr())|| Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.REFUND_AMOUNT.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.PAYMENTS.getAttr()));
                }
                break;
            case RETURNED_PURCHASE:
                if (isImport) {
                    fieldAttrList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.INVOICES.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS.getAttr())|| Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.RETURNED_PURCHASE_AMOUNT.getAttr()));
                }
                break;
            case ORI_STOCK:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), OriStockEnum.WAREHOUSE.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
                        setOriStockWareHouseToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case STOCK_FLOW_BILL:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), StockFlowBillEnum.OUT_IN_RECORD.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), StockFlowBillEnum.REMAINING_STOCK.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.SUB_FORM.getType());
                    }
                }
                break;
            case BATCH_FLOW_BILL:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), BatchFlowBillEnum.OUT_IN_RECORD.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), BatchFlowBillEnum.REMAINING_STOCK.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.SUB_FORM.getType());
                    }
                }
                break;
            case STOCK_STANDING_BOOK:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), StockStandingBookEnum.ORI_STOCK.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), StockStandingBookEnum.PERIOD_INSTOCK.getAttr())
                        || Objects.equals(fieldAttrEntity.getAttr(), StockStandingBookEnum.PERIOD_OUTSTOCK.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), StockStandingBookEnum.REMAINING_STOCK.getAttr())) {
                        fieldAttrEntity.setFieldType(FieldTypeEnum.SUB_FORM.getType());
                    }
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), DistributorEnum.AREA.getAttr())) {
                        setAreaToCombo(fieldAttrEntity, excelTemplateDTO);
                    }
                }
                break;
            case RECEIPT_ORDER:
                if (!isImport){
                    List<String> removeAttrList = Arrays.asList(ReceiptOrderEnum.LINK_WORK_ORDER_HIDE.getAttr(), ReceiptOrderEnum.LINK_CUSTOMER_HIDE.getAttr());
                    fieldAttrList.removeIf(entity -> removeAttrList.contains(entity.getAttr()));
                }
                break;
            case WORK_ORDER_V2:
                if (isImport){
                    fieldAttrList.removeIf(entity -> {
                        //过滤新建不展示字段
                        return Objects.equals(entity.getIsRedundant(), 0) && !showTypeList.contains(entity.getShowType());
                    });
                }else {
                    fieldAttrList.removeIf(entity -> {
                        //过滤取消时间、关联客户隐藏、节点type隐藏、是否在工单池
                        return Objects.equals(entity.getAttr(), "date_5") || Objects.equals(entity.getAttr(), "text_13")
                                || Objects.equals(entity.getAttr(), "text_15") || Objects.equals(entity.getAttr(), "num_6")
                                || (Objects.equals(entity.getIsRedundant(), 0) && !showTypeList.contains(entity.getShowType()));
                    });
                }
            case SERVICE_PROJECT:
                if (isImport){
                    fieldAttrList.removeIf(entity -> {
                        //过滤创建人
                        return Objects.equals(entity.getAttr(), "creatorId");
                    });
                }
            default:
                break;
        }
        if (Objects.nonNull(excelTemplateDTO.getOnlyGetAttrs())) {
            // 单纯获取字段解释不需要在必填字段上打*号，所以这边直接返回
            return JSON.parseArray(JSON.toJSONString(fieldAttrList));
        }
        // 必填字段的title显示一个*号,分行的加^
        if (!Objects.equals(excelTemplateDTO.getPartialExport(),1)){
            setTitleTag(fieldAttrList);
        }
        return JSON.parseArray(JSON.toJSONString(fieldAttrList));
    }

    private void addGuaranteeSearchAttr(List<FieldAttrEntityForImport> fieldAttrList) {
        int unit = 0;
        FieldAttrEntity costFieldAttr = null;
        FieldAttrEntity stockFieldAttr = null;
        for (int i = 0; i < fieldAttrList.size(); i ++) {
            FieldAttrEntityForImport forImport = fieldAttrList.get(i);
            if (Objects.equals(ProductEnum.COST.getAttr(), forImport.getAttr())) {
                costFieldAttr = forImport;
            } else if (Objects.equals(ProductEnum.STOCK.getAttr(), forImport.getAttr())) {
                stockFieldAttr = forImport;
            } else if (Objects.equals(forImport.getAttr(), ProductEnum.UNIT.getAttr())) {
                unit = i;
            }
        }
        List<FieldAttrEntityForImport> addList = new ArrayList<>();
        FieldAttrEntityForImport batchEntityForImport = new FieldAttrEntityForImport();
        batchEntityForImport.setAttr(SelectProductEnum.BATCH.getSaasAttr());
        batchEntityForImport.setAttrName(StockProductEnum.BATCH.getAttrName());
        batchEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(batchEntityForImport);

        FieldAttrEntityForImport produceDateEntityForImport = new FieldAttrEntityForImport();
        produceDateEntityForImport.setAttr(SelectProductEnum.PRODUCE_DATE.getSaasAttr());
        produceDateEntityForImport.setAttrName(StockProductEnum.PRODUCE_DATE.getAttrName());
        produceDateEntityForImport.setFieldType(FieldTypeEnum.DATETIME.getType());
        addList.add(produceDateEntityForImport);

        FieldAttrEntityForImport guaranteePeriodEntityForImport = new FieldAttrEntityForImport();
        guaranteePeriodEntityForImport.setAttr(SelectProductEnum.GUARANTEE_PERIOD.getSaasAttr());
        guaranteePeriodEntityForImport.setAttrName(StockProductEnum.GUARANTEE_PERIOD.getAttrName());
        guaranteePeriodEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(guaranteePeriodEntityForImport);
        FieldAttrEntityForImport expireDateEntityForImport = new FieldAttrEntityForImport();
        expireDateEntityForImport.setAttr(SelectProductEnum.EXPIRE_DATE.getSaasAttr());
        expireDateEntityForImport.setAttrName(StockProductEnum.EXPIRE_PERIOD.getAttrName());
        expireDateEntityForImport.setFieldType(FieldTypeEnum.DATETIME.getType());
        addList.add(expireDateEntityForImport);

        FieldAttrEntityForImport fieldAttrEntityForImport = new FieldAttrEntityForImport();
        fieldAttrEntityForImport.setAttr(SelectProductEnum.WAREHOUSE.getSaasAttr());
        fieldAttrEntityForImport.setAttrName(SelectProductEnum.WAREHOUSE.getAttrName());
        fieldAttrEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(fieldAttrEntityForImport);
        // 库存数量
        FieldAttrEntityForImport stockField = new FieldAttrEntityForImport();
        stockField.setAttr(SelectProductEnum.STOCK.getSaasAttr());
        stockField.setAttrName(SelectProductEnum.STOCK.getAttrName());
        stockField.setFieldType(SelectProductEnum.STOCK.getFieldType());
        if (Objects.nonNull(stockFieldAttr)) {
            stockField.setVisible(stockFieldAttr.getVisible());
            stockField.setVisibleScopeRule(stockFieldAttr.getVisibleScopeRule());
            stockField.setVisibleScopeEnable(stockFieldAttr.getVisibleScopeEnable());
        } else {
            stockField.setVisible(1);
        }
        addList.add(stockField);
        // 成本
        FieldAttrEntityForImport costField = new FieldAttrEntityForImport();
        costField.setAttr(SelectProductEnum.COST.getSaasAttr());
        costField.setAttrName(SelectProductEnum.COST.getAttrName());
        costField.setFieldType(SelectProductEnum.COST.getFieldType());
        if (Objects.nonNull(costFieldAttr)) {
            costField.setVisible(costFieldAttr.getVisible());
            costField.setVisibleScopeRule(costFieldAttr.getVisibleScopeRule());
            costField.setVisibleScopeEnable(costFieldAttr.getVisibleScopeEnable());
        } else {
            costField.setVisible(1);
        }
        addList.add(costField);
        // 成本小计
        FieldAttrEntityForImport totalCostField = new FieldAttrEntityForImport();
        totalCostField.setAttr(SelectProductEnum.TOTAL_COST.getSaasAttr());
        totalCostField.setAttrName(SelectProductEnum.TOTAL_COST.getAttrName());
        totalCostField.setFieldType(SelectProductEnum.TOTAL_COST.getFieldType());
        if (Objects.nonNull(costFieldAttr)) {
            totalCostField.setVisible(costFieldAttr.getVisible());
            totalCostField.setVisibleScopeRule(costFieldAttr.getVisibleScopeRule());
            totalCostField.setVisibleScopeEnable(costFieldAttr.getVisibleScopeEnable());
        } else {
            totalCostField.setVisible(1);
        }
        addList.add(totalCostField);
        // 剩余天数
        FieldAttrEntityForImport fieldStockSearch = new FieldAttrEntityForImport();
        fieldStockSearch.setAttr(ListOptionEnum.GUARANTEE_SEARCH.getAttr());
        fieldStockSearch.setAttrName(ListOptionEnum.GUARANTEE_SEARCH.getAttrName());
        fieldStockSearch.setFieldType(FieldTypeEnum.TEXT.getType());
        fieldAttrList.addAll(unit + 1, addList);
        fieldAttrList.add(fieldAttrList.size() , fieldStockSearch);
        fieldAttrList.removeIf(field -> Objects.equals(field.getAttr(), ProductEnum.STOCK.getAttr()) || Objects.equals(field.getAttr(), ProductEnum.COST.getAttr()));
    }

    private void addWarningSearchAttr(List<FieldAttrEntityForImport> fieldAttrList, FieldAttrEntityForImport stockAttr) {
        /*int i = 0;
        for (FieldAttrEntityForImport forImport : fieldAttrList) {
            if (Objects.equals(forImport.getAttr(), ProductEnum.STOCK.getAttr())) {
                break;
            }
            i++;
        }*/

        List<FieldAttrEntityForImport> addList = new ArrayList<>();
        FieldAttrEntityForImport warningTypeEntityForImport = new FieldAttrEntityForImport();
        warningTypeEntityForImport.setAttr("warningType");
        warningTypeEntityForImport.setAttrName(I18nMessageUtil.getMessage(BusinessConstant.WARNING_TYPE_CHINESE));
        warningTypeEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(warningTypeEntityForImport);

        FieldAttrEntityForImport currentStockEntityForImport =  stockAttr == null ? new FieldAttrEntityForImport() : stockAttr;
        currentStockEntityForImport.setAttr("currentStock");
        currentStockEntityForImport.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.CURRENT_STOCK));
        currentStockEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(currentStockEntityForImport);

        FieldAttrEntityForImport upperLimitEntityForImport = new FieldAttrEntityForImport();
        upperLimitEntityForImport.setAttr("upperLimit");
        upperLimitEntityForImport.setAttrName(SubOptionTableHeadEnum.WARNING_UPPER_LIMIT.getLabel());
        upperLimitEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(upperLimitEntityForImport);

        FieldAttrEntityForImport lowerLimitEntityForImport = new FieldAttrEntityForImport();
        lowerLimitEntityForImport.setAttr("lowerLimit");
        lowerLimitEntityForImport.setAttrName(SubOptionTableHeadEnum.WARNING_LOWER_LIMIT.getLabel());
        lowerLimitEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(lowerLimitEntityForImport);

        FieldAttrEntityForImport overLimitEntityForImport = new FieldAttrEntityForImport();
        overLimitEntityForImport.setAttr("overLimit");
        overLimitEntityForImport.setAttrName(FieldTypeEnum.WARNING_SEARCH.getDescription());
        overLimitEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        addList.add(overLimitEntityForImport);
        fieldAttrList.addAll(addList);
    }

    private void addWareHouseAttr(List<FieldAttrEntityForImport> fieldAttrList) {
        FieldAttrEntityForImport fieldAttrEntityForImport = new FieldAttrEntityForImport();
        fieldAttrEntityForImport.setAttr(ProductEnum.WAREHOUSE.getAttr());
        fieldAttrEntityForImport.setAttrName(ProductEnum.WAREHOUSE.getAttrName());
        fieldAttrEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
        int i = 0;
        for (FieldAttrEntityForImport forImport : fieldAttrList) {
            if (Objects.equals(forImport.getAttr(), ProductEnum.STOCK.getAttr())) {
                break;
            }
            i++;
        }
        fieldAttrList.add(i, fieldAttrEntityForImport);
    }

    public void handleCommunicateBusiness(List<FieldAttrEntityForImport> fieldAttrList, String corpid) throws XbbException{
        for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
            if (Objects.equals(fieldAttrEntity.getAttr(), CommunicateBaseEnum.COMMUNICATE_BUSINESS.getAttr())) {
                List<FieldAttrEntityForImport> subFormFieldAttrList = new ArrayList<>();
                List<ItemPoJo> items = fieldAttrEntity.getItems();
                FieldAttrEntityForImport typeField = new FieldAttrEntityForImport();
                typeField.setItems(items);
                BeanUtil.copyProperties(ImportEnum.COMMUNICATE_BUSINESS_TYPE, typeField);
                typeField.setFieldType(FieldTypeEnum.COMBO.getType());
                subFormFieldAttrList.add(typeField);
                FieldAttrEntityForImport nameField = new FieldAttrEntityForImport();
                BeanUtil.copyProperties(ImportEnum.COMMUNICATE_NAME, nameField);
                subFormFieldAttrList.add(nameField);
                SubFormPoJo subFormPoJo = new SubFormPoJo();
                subFormPoJo.setItems(subFormFieldAttrList);
                fieldAttrEntity.setSubForm(subFormPoJo);
                fieldAttrEntity.setFieldType(FieldTypeEnum.SUB_FORM.getType());
            } /*else if (Objects.equals(fieldAttrEntity.getSaasAttr(), CustomerCommunicateEnum.CUSTOMER_STATUS.getSaasAttr())) {
                List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STATUS,corpid,null);
                fieldAttrEntity.setItems(itemPoJoList);
            }*/
        }
    }

    @Override
    public void setTitleTag(List<FieldAttrEntityForImport> fieldAttrList) {
        for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.setTitleNeedSeparatelyTag(fieldAttrEntity);
                importHelper.setTitleRequiredTag(fieldAttrEntity);
                List<FieldAttrEntityForImport> subFormFieldAttrList = JSON.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntityForImport.class);
                // 上边转化了一次attrName 和 attrName_en(国际化)
                // 再转化一次
                if (fieldAttrEntity.getAttr().contains("subForm_") && Objects.equals(fieldAttrEntity.getIsRedundant(), BasicConstant.ZERO)) {
                    subFormFieldAttrList.forEach(item -> {
                        item.changeAttrName();
                    });
                }
                setTitleTag(subFormFieldAttrList);
                fieldAttrEntity.getSubForm().setItems(subFormFieldAttrList);
            /*} else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.IMAGE.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())) {
                fieldAttrEntity.setNeedImportSeparately(ImportConstant.NEED_IMPORT_SEPARATELY);
                importHelper.setTitleNeedSeparatelyTag(fieldAttrEntity);*/
            } else {
                importHelper.setTitleRequiredTag(fieldAttrEntity);
            }
        }
    }

    @Override
    public void handleLabelFields(List<FieldAttrEntityForImport> fieldAttrList, FormDataListDTO formDataListDTO) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(formDataListDTO) && Objects.isNull(formDataListDTO.getIsContact())) {
            param.put("corpid", formDataListDTO.getCorpid());
            param.put("appId", formDataListDTO.getAppId());
            param.put("formId", formDataListDTO.getFormId());
            param.put("del", DelEnum.NORMAL.getDel());
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.LABEL.getType())){
                    List<ItemPoJo> itemes = new ArrayList<>();
                    for (LabelEntity entity : entitys) {
                        ItemPoJo itemPoJo = new ItemPoJo();;
                        itemPoJo.setText(entity.getName());
                        itemPoJo.setValue(entity.getId());
                        itemes.add(itemPoJo);
                    }
                    fieldAttrEntityForImport.setItems(itemes);
                    break;
                }
            }
        } else if (Objects.nonNull(formDataListDTO) && Objects.equals(formDataListDTO.getIsContact(), BasicConstant.ONE)){
            PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTACT.getCode(), formDataListDTO.getCorpid());
            param.clear();
            param.put("corpid", contactExplain.getCorpid());
            param.put("appId", contactExplain.getAppId());
            param.put("formId", contactExplain.getFormId());
            param.put("del", DelEnum.NORMAL.getDel());
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            if (CollectionsUtil.isNotEmpty(entitys)) {
                for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.LABEL.getType())){
                        List<ItemPoJo> itemes = new ArrayList<>();
                        for (LabelEntity entity : entitys) {
                            ItemPoJo itemPoJo = new ItemPoJo();;
                            itemPoJo.setText(entity.getName());
                            itemPoJo.setValue(entity.getId());
                            itemes.add(itemPoJo);
                        }
                        fieldAttrEntityForImport.setItems(itemes);
                        break;
                    }
                }
            }
        }
    }


    @Override
    public void parseWaitPurchaseExplains(ExcelExplainGetDTO excelExplainGetDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException{
        Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
        if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT.getCode())){
            while (iterator.hasNext()) {
                FieldAttrEntityForImport fieldAttrEntityForImport = iterator.next();
                String attr = fieldAttrEntityForImport.getAttr();
                if (!(Objects.equals(attr, WaitOutstockEnum.CONTRACT_NO.getAttr())
                        || Objects.equals(attr, WaitOutstockEnum.NAME.getAttr())
                        || Objects.equals(attr, WaitOutstockEnum.LINK_CUSTOMER.getAttr())
                        || Objects.equals(attr, WaitOutstockEnum.CREATOR_ID.getAttr())
                        || Objects.equals(attr, WaitOutstockEnum.ADD_TIME.getAttr())
                        || Objects.equals(attr, WaitOutstockEnum.UPDATE_TIME.getAttr()))) {
                    iterator.remove();
                }
                fieldAttrEntityForImport.setEditable(0);
            }
            PaasFormExplainEntity paasFormExplainEnt = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTRACT.getCode(), excelExplainGetDTO.getCorpid());
            List<FieldAttrEntityForImport> explains = JSON.parseArray(paasFormExplainEnt.getExplains(), FieldAttrEntityForImport.class);
            for (FieldAttrEntityForImport fieldAttrEntityForImport : explains){
                if (Objects.equals(fieldAttrEntityForImport.getAttr(),ContractEnum.PRODUCT.getAttr())){
                    fieldAttrEntityForImport.setAttrName("待采购产品");
                    fieldAttrList.add(fieldAttrEntityForImport);
                    break;
                }
            }
        }else if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())){
            PaasFormExplainEntity paasFormExplainEntityProduct = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),excelExplainGetDTO.getCorpid());
            if (paasFormExplainEntityProduct == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //处理产品解释
            while (iterator.hasNext()) {
                FieldAttrEntityForImport fieldAttrEntityForImport = iterator.next();
                String attr = fieldAttrEntityForImport.getAttr();
                if (!(Objects.equals(attr, WaitPurchaseProductEnum.PRODUCT_IMGS.getAttr())
                        || Objects.equals(attr, ProductEnum.NAME.getAttr())
                        || Objects.equals(attr, ProductEnum.SERIALNO.getAttr())
                        || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                        || Objects.equals(attr, ProductEnum.SUPPLIER.getAttr()))) {
                    iterator.remove();
                }
                fieldAttrEntityForImport.setEditable(0);
            }
            for (FieldAttrEntityForImport fieldAttrEntityForImport:fieldAttrList){
                if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.SERIALNO.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitPurchaseProductEnum.PRODUCT_NO.getAttr());
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.NAME.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitPurchaseProductEnum.PRODUCT_NAME.getAttr());
                    fieldAttrEntityForImport.setAttrName(WaitOutstockEnum.PRODUCT_NAME.getAttrName());
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitPurchaseProductEnum.SPECIFICATION.getAttr());
                }
            }
            // 已采购数量
            FieldAttrEntityForImport purchaseNum = new FieldAttrEntityForImport();
            purchaseNum.setAttr(WaitPurchaseProductEnum.PURCHASE_NUM.getAttr());
            purchaseNum.setAttrName(WaitPurchaseProductEnum.PURCHASE_NUM.getAttrName());
            purchaseNum.setFieldType(WaitPurchaseProductEnum.PURCHASE_NUM.getFieldType());
            purchaseNum.setSaasAttr(WaitPurchaseProductEnum.PURCHASE_NUM.getSaasAttr());
            purchaseNum.setLinkedType(WaitPurchaseProductEnum.PURCHASE_NUM.getLinkedType());
            purchaseNum.setDisableListSort(0);
            fieldAttrList.add(purchaseNum);
            // 已入库
            FieldAttrEntityForImport instockNum = new FieldAttrEntityForImport();
            instockNum.setAttr(WaitPurchaseProductEnum.INSTOCK_NUM.getAttr());
            instockNum.setAttrName(WaitPurchaseProductEnum.INSTOCK_NUM.getAttrName());
            instockNum.setFieldType(WaitPurchaseProductEnum.INSTOCK_NUM.getFieldType());
            instockNum.setSaasAttr(WaitPurchaseProductEnum.INSTOCK_NUM.getSaasAttr());
            instockNum.setLinkedType(WaitPurchaseProductEnum.INSTOCK_NUM.getLinkedType());
            instockNum.setDisableListSort(0);
            fieldAttrList.add(instockNum);
            // 出库数量
            // 已入库
            FieldAttrEntityForImport outstockNum = new FieldAttrEntityForImport();
            outstockNum.setAttr(WaitPurchaseProductEnum.OUTSTOCK_NUM.getAttr());
            outstockNum.setAttrName(WaitPurchaseProductEnum.OUTSTOCK_NUM.getAttrName());
            outstockNum.setFieldType(WaitPurchaseProductEnum.OUTSTOCK_NUM.getFieldType());
            outstockNum.setSaasAttr(WaitPurchaseProductEnum.OUTSTOCK_NUM.getSaasAttr());
            outstockNum.setLinkedType(WaitPurchaseProductEnum.OUTSTOCK_NUM.getLinkedType());
            outstockNum.setDisableListSort(0);
            fieldAttrList.add(outstockNum);
            // 未出库数量
            FieldAttrEntityForImport waitOutstockNum = new FieldAttrEntityForImport();
            waitOutstockNum.setAttr(WaitPurchaseProductEnum.WAIT_OUTSTOCK_NUM.getAttr());
            waitOutstockNum.setAttrName(WaitPurchaseProductEnum.WAIT_OUTSTOCK_NUM.getAttrName());
            waitOutstockNum.setFieldType(WaitPurchaseProductEnum.WAIT_OUTSTOCK_NUM.getFieldType());
            waitOutstockNum.setSaasAttr(WaitPurchaseProductEnum.WAIT_OUTSTOCK_NUM.getSaasAttr());
            waitOutstockNum.setLinkedType(WaitPurchaseProductEnum.WAIT_OUTSTOCK_NUM.getLinkedType());
            waitOutstockNum.setDisableListSort(0);
            fieldAttrList.add(waitOutstockNum);
            // 处理合同字段解释
            Map<String, Object> paasFormParam = new HashMap<>();
            paasFormParam.put("corpid", excelExplainGetDTO.getCorpid());
            paasFormParam.put("enable", 1);
            paasFormParam.put("del", 0);
            paasFormParam.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
            paasFormParam.put("businessType", XbbRefTypeEnum.CONTRACT.getCode());
            paasFormParam.put("orderByStr", "sort ASC ");
            List<PaasFormEntity> paasFormEntityList = paasFormModel.findEntity(paasFormParam);
            if (CollectionsUtil.isNotEmpty(paasFormEntityList)){
                Long formId = paasFormEntityList.get(0).getId();
                PaasFormExplainEntity contractExplains = paasFormExplainModel.getByFormId(formId, excelExplainGetDTO.getCorpid());
                List<FieldAttrEntityForImport> contractExplainList = JSON.parseArray(contractExplains.getExplains(), FieldAttrEntityForImport.class);
                contractExplainList.forEach(item -> {
                    if (Objects.equals(item.getAttr(),ContractEnum.PRODUCT.getAttr())){
                        List<FieldAttrEntity> items = (List<FieldAttrEntity>) item.getSubForm().getItems();
                        items.forEach(itm ->{
                            if (Objects.equals(ContractProductEnum.UNIT.getAttr(),itm.getAttr()) || Objects.equals(ContractProductEnum.MEMO.getAttr(),itm.getAttr()) || Objects.equals(ContractProductEnum.NUM.getAttr(),itm.getAttr())){
                                if (Objects.equals(ContractProductEnum.NUM.getAttr(),itm.getAttr())){
                                    itm.setSaasAttr("productNum");
                                    itm.setAttrName("销售数量");
                                }
                                // 单位
                                FieldAttrEntityForImport unitAttr = new FieldAttrEntityForImport();
                                unitAttr.setAttr(itm.getAttr());
                                unitAttr.setAttrName(itm.getAttrName());
                                unitAttr.setFieldType(itm.getFieldType());
                                unitAttr.setSaasAttr(itm.getSaasAttr());
                                unitAttr.setLinkedType(itm.getLinkedType());
                                fieldAttrList.add(unitAttr);
                            }
                        });
                    }
                });
                Iterator<FieldAttrEntityForImport> iterators = contractExplainList.iterator();
                while (iterators.hasNext()) {
                    FieldAttrEntityForImport fieldAttrEntityForImport = iterators.next();
                    String attr = fieldAttrEntityForImport.getAttr();
                    if (!(Objects.equals(attr, WaitOutstockEnum.CONTRACT_NO.getAttr())
                            || Objects.equals(attr, WaitOutstockEnum.NAME.getAttr())
                            || Objects.equals(attr, WaitOutstockEnum.LINK_CUSTOMER.getAttr())
                            || Objects.equals(attr, WaitOutstockEnum.CREATOR_ID.getAttr())
                            || Objects.equals(attr, WaitOutstockEnum.ADD_TIME.getAttr())
                            || Objects.equals(attr, WaitOutstockEnum.UPDATE_TIME.getAttr()))) {
                        iterators.remove();
                    }
                    fieldAttrEntityForImport.setEditable(0);
                }
                fieldAttrList.addAll(contractExplainList);
            }
        }
    }
    @Override
    public void parseSmartReplenishmentExplains(ExcelExplainGetDTO excelExplainGetDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException{
        String corpid = excelExplainGetDTO.getCorpid();
        //处理产品解释

        Iterator<FieldAttrEntityForImport> iteratorProduct = fieldAttrList.iterator();
        while (iteratorProduct.hasNext()) {
            FieldAttrEntityForImport fieldAttrEntityForImport = iteratorProduct.next();
            String attr = fieldAttrEntityForImport.getAttr();
            if (!( Objects.equals(attr, ProductEnum.NAME.getAttr())
                    || Objects.equals(attr, ProductEnum.SERIALNO.getAttr())
                    || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                    || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                    || Objects.equals(attr, ProductEnum.SUPPLIER.getAttr()))
                    || Objects.equals(attr, ProductEnum.STOCK.getAttr())) {
                iteratorProduct.remove();
            }
            fieldAttrEntityForImport.setEditable(0);
        }
        FieldAttrEntityForImport waitOutstockNumField = new FieldAttrEntityForImport();
        waitOutstockNumField.setAttr("waitOutstockNum");
        waitOutstockNumField.setAttrName("未出库数量");
        waitOutstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
        waitOutstockNumField.setVisible(1);
        fieldAttrList.add(waitOutstockNumField);
        // 获取公司级配置 拿到该公司下的智能补货公式
        boolean enablePurchasePassage = false;
        boolean enableMiniStock = false;
        // 采购在途公司级配置
        CompanyConfigEntity purchasePassageConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_PURCHASE_PASSAGE.getAlias(), corpid);
        // 最低库存公司级配置
        CompanyConfigEntity miniStockConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_MINI_STOCK.getAlias(), corpid);
        if (Objects.isNull(purchasePassageConfig) || Objects.equals(BasicConstant.IS_USE.toString(),purchasePassageConfig.getConfigValue())){
            enablePurchasePassage = true;
        }
        if (Objects.isNull(miniStockConfig) || Objects.equals(BasicConstant.IS_USE.toString(),miniStockConfig.getConfigValue())){
            enableMiniStock = true;
        }
        // 采购在途数量
        if(enablePurchasePassage){
            FieldAttrEntityForImport pendingInstockNumField = new FieldAttrEntityForImport();
            pendingInstockNumField.setAttr("pendingInstockNum");
            pendingInstockNumField.setAttrName("待入库数量");
            pendingInstockNumField.setFieldType(FieldTypeEnum.NUM.getType());
            pendingInstockNumField.setVisible(1);
            pendingInstockNumField.setDisableListSort(1);
            fieldAttrList.add(pendingInstockNumField);
        }
        if (enableMiniStock){
            // 最低库存
            FieldAttrEntityForImport miniNumField = new FieldAttrEntityForImport();
            miniNumField.setAttr("miniNum");
            miniNumField.setAttrName("最低库存");
            miniNumField.setFieldType(FieldTypeEnum.NUM.getType());
            miniNumField.setVisible(1);
            fieldAttrList.add(miniNumField);
        }
    }
    @Override
    public void waitOutstockExplains(ExcelExplainGetDTO excelExplainGetDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException{
        Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntityForImport fieldAttrEntityForImport = iterator.next();
            String attr = fieldAttrEntityForImport.getAttr();
            if (!(Objects.equals(attr, WaitOutstockEnum.CONTRACT_NO.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.NAME.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.LINK_CUSTOMER.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.SIGN_TIME.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.STATUS.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.OWNER_ID.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.MINOR_USER.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.CREATOR_ID.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.ADD_TIME.getAttr())
                    || Objects.equals(attr, WaitOutstockEnum.UPDATE_TIME.getAttr()))) {
                iterator.remove();
            }
            fieldAttrEntityForImport.setEditable(0);
        }
        if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT.getCode())){
            PaasFormExplainEntity paasFormExplainEnt = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTRACT.getCode(), excelExplainGetDTO.getCorpid());
            List<FieldAttrEntityForImport> explains = JSON.parseArray(paasFormExplainEnt.getExplains(), FieldAttrEntityForImport.class);
            for (FieldAttrEntityForImport fieldAttrEntityForImport : explains){
                if (Objects.equals(fieldAttrEntityForImport.getAttr(),ContractEnum.PRODUCT.getAttr())){
                    fieldAttrEntityForImport.setAttrName("待出库产品");
                    fieldAttrList.add(fieldAttrEntityForImport);
                    break;
                }
            }
        }else if (Objects.equals(excelExplainGetDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())){
            PaasFormExplainEntity paasFormExplainEntityProduct = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),excelExplainGetDTO.getCorpid());
            if (paasFormExplainEntityProduct == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //处理产品解释
            List<FieldAttrEntityForImport> explainListProduct = JSONArray.parseArray(paasFormExplainEntityProduct.getExplains(), FieldAttrEntityForImport.class);
            Iterator<FieldAttrEntityForImport> iteratorProduct = explainListProduct.iterator();
            while (iteratorProduct.hasNext()) {
                FieldAttrEntityForImport fieldAttrEntityForImport = iteratorProduct.next();
                String attr = fieldAttrEntityForImport.getAttr();
                if (!(Objects.equals(attr, WaitOutstockEnum.PRODUCT_IMGS.getAttr())
                        || Objects.equals(attr, ProductEnum.NAME.getAttr())
                        || Objects.equals(attr, ProductEnum.SERIALNO.getAttr())
                        || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                        || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                        || Objects.equals(attr, ProductEnum.STOCK.getAttr()))) {
                    iteratorProduct.remove();
                }
                fieldAttrEntityForImport.setEditable(0);
            }
            for (FieldAttrEntityForImport fieldAttrEntityForImport:explainListProduct){
                if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.SERIALNO.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitOutstockEnum.PRODUCT_NO.getAttr());
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.NAME.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitOutstockEnum.PRODUCT_NAME.getAttr());
                    fieldAttrEntityForImport.setAttrName(WaitOutstockEnum.PRODUCT_NAME.getAttrName());
                    fieldAttrEntityForImport.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                    fieldAttrEntityForImport.setAttr(WaitOutstockEnum.SPECIFICATION.getAttr());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.UNIT.getAttr())){
                    fieldAttrEntityForImport.setAttrName(WaitOutstockEnum.UNIT.getAttrName());
                }else if(Objects.equals(fieldAttrEntityForImport.getAttr(),ProductEnum.STOCK.getAttr())){
                    fieldAttrEntityForImport.setAttrName(WaitOutstockEnum.STOCK.getAttrName());
                }
            }
            FieldAttrEntityForImport waitOutStockField = new FieldAttrEntityForImport();
            waitOutStockField.setAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttr());
            waitOutStockField.setAttrName(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName());
            waitOutStockField.setFieldType(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getFieldType());
            waitOutStockField.setSaasAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getSaasAttr());
            waitOutStockField.setLinkedType(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getLinkedType());
            waitOutStockField.setDisableListSort(0);
            waitOutStockField.setIsRedundant(1);
            fieldAttrList.add(waitOutStockField);
            FieldAttrEntityForImport memoField = new FieldAttrEntityForImport();
            memoField.setAttr(WaitOutstockEnum.MEMO.getAttr());
            memoField.setAttrName(WaitOutstockEnum.MEMO.getAttrName());
            memoField.setFieldType(WaitOutstockEnum.MEMO.getFieldType());
            memoField.setSaasAttr(WaitOutstockEnum.MEMO.getSaasAttr());
            memoField.setLinkedType(WaitOutstockEnum.MEMO.getLinkedType());
            memoField.setDisableListSort(0);
            explainListProduct.add(memoField);
            fieldAttrList.addAll(explainListProduct);
        }
    }

    /**
     * 处理工作报告业绩数据解释
     *
     * @param subBusinessType 类型
     * @param fieldAttrEntity 业务数据
     */
    private void handleWorkReportStatisticDataExplain(Integer subBusinessType, FieldAttrEntityForImport fieldAttrEntity) {
        String customerAttrName;
        String communicateAttrName;
        String opportunityAttrName;
        String opportunityAmountAttrName;
        String contractAttrName;
        String contractAmountAttrName;
        String paymentAddAttrName;
        if (Objects.equals(subBusinessType, XbbRefTypeEnum.WORKREPORT_DAILY.getCode())) {
            customerAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CUSTOMER);
            communicateAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_COMMUNICATE);
            opportunityAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_OPPORTUNITY);
            opportunityAmountAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_OPPORTUNITY_AMOUNT);
            contractAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CONTRACT);
            contractAmountAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CONTRACT_AMOUNT);
            paymentAddAttrName = I18nMessageUtil.getMessage(CommonConstant.TODAY) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_PAYMENT_AMOUNT);
        } else if (Objects.equals(subBusinessType, XbbRefTypeEnum.WORKREPORT_MONTHLY.getCode())) {
            customerAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CUSTOMER);
            communicateAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_COMMUNICATE);
            opportunityAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_OPPORTUNITY);
            opportunityAmountAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_OPPORTUNITY_AMOUNT);
            contractAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CONTRACT);
            contractAmountAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CONTRACT_AMOUNT);
            paymentAddAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_MONTH) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_PAYMENT_AMOUNT);
        } else {
            customerAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CUSTOMER);
            communicateAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_COMMUNICATE);
            opportunityAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_OPPORTUNITY);
            opportunityAmountAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_OPPORTUNITY_AMOUNT);
            contractAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CONTRACT);
            contractAmountAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_CONTRACT_AMOUNT);
            paymentAddAttrName = I18nMessageUtil.getMessage(CommonConstant.THIS_WEEK) + I18nMessageUtil.getMessage(I18nStringConstant.ADD_PAYMENT_AMOUNT);
        }
        List<FieldAttrEntity> statisticFieldList = new ArrayList<>();
        FieldAttrEntity customerAddField = new FieldAttrEntity();
        customerAddField.setAttr("customerAddCount");
        customerAddField.setAttrName(customerAttrName);
        statisticFieldList.add(customerAddField);
        FieldAttrEntity communicateAddField = new FieldAttrEntity();
        communicateAddField.setAttr("communicateAddCount");
        communicateAddField.setAttrName(communicateAttrName);
        statisticFieldList.add(communicateAddField);
        FieldAttrEntity opportunityAddField = new FieldAttrEntity();
        opportunityAddField.setAttr("opportunityAddCount");
        opportunityAddField.setAttrName(opportunityAttrName);
        statisticFieldList.add(opportunityAddField);
        FieldAttrEntity opportunityAmountAddField = new FieldAttrEntity();
        opportunityAmountAddField.setAttr("oppAmount");
        opportunityAmountAddField.setAttrName(opportunityAmountAttrName);
        statisticFieldList.add(opportunityAmountAddField);
        FieldAttrEntity contractAddField = new FieldAttrEntity();
        contractAddField.setAttr("contractAddCount");
        contractAddField.setAttrName(contractAttrName);
        statisticFieldList.add(contractAddField);
        FieldAttrEntity contractAmountAddField = new FieldAttrEntity();
        contractAmountAddField.setAttr("contractAmount");
        contractAmountAddField.setAttrName(contractAmountAttrName);
        statisticFieldList.add(contractAmountAddField);
        FieldAttrEntity paymentAddField = new FieldAttrEntity();
        paymentAddField.setAttr("paymentSheetAmount");
        paymentAddField.setAttrName(paymentAddAttrName);
        statisticFieldList.add(paymentAddField);
        fieldAttrEntity.setFieldType(FieldTypeEnum.SUB_FORM.getType());
        setSpecialFields2SubForm(fieldAttrEntity, statisticFieldList);
    }


    @Override
    public List<CellTitlePojo> getExcelTitle(Workbook workBook, int titleRowIndex, Workbook tempExcel) throws XbbException {
        List<CellTitlePojo> titleList = new ArrayList<>();
        Sheet sheet = workBook.getSheetAt(0);
        Sheet tempSheet = tempExcel.getSheetAt(0);
        Row titleRow = tempSheet.getRow(titleRowIndex);
        if (Objects.isNull(titleRow)) {
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235002);
        }
        int cellColumnNum = titleRow.getLastCellNum();

        boolean hasSubForm = false;
        for (int titleColumnIndex = 0; titleColumnIndex < cellColumnNum; titleColumnIndex++) {
            MergeRegionRangePojo mergeRegionRangePojo = ExcelUtil.isMergedRegion(sheet, titleRowIndex, titleColumnIndex);
            if (Objects.isNull(titleRow.getCell(titleColumnIndex))) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.EXCEL_TITLE_EMPTY, titleColumnIndex + 1);
            }
            String title = titleRow.getCell(titleColumnIndex).getStringCellValue();
            if (mergeRegionRangePojo.getIsMergedCell() || title.indexOf(ImportConstant.TITLE_CAN_IMPORT_SEPARATELY) != -1) {
                hasSubForm = true;
                break;
            }
        }
        String title = "";
        String subTitle;
        String subSubTitle;
        String subSubSubTitle;
        boolean hasSubMark;
        try {
            for (int titleColumnIndex = 0; titleColumnIndex < cellColumnNum; ) {
                if (titleRow.getCell(titleColumnIndex) != null) {
                    title = titleRow.getCell(titleColumnIndex).getStringCellValue();
                }
                if (hasSubForm) {
                    MergeRegionRangePojo mergeRegionRangePojo = ExcelUtil.isMergedRegion(sheet, titleRowIndex, titleColumnIndex);
                    boolean singleRowSubForm = !mergeRegionRangePojo.getIsMergedCell();
                    boolean multiRowSubForm = mergeRegionRangePojo.getIsMergedCell() && !Objects.equals(mergeRegionRangePojo.getFirstColumn(), mergeRegionRangePojo.getLastColumn());
                    hasSubMark = title.indexOf(ImportConstant.TITLE_CAN_IMPORT_SEPARATELY) != -1;
                    if (singleRowSubForm || multiRowSubForm || hasSubMark) {
                        Row subTitleRow = tempSheet.getRow(titleRowIndex + 1);
                        for (int subFormColumn = mergeRegionRangePojo.getFirstColumn(); subFormColumn <= mergeRegionRangePojo.getLastColumn(); subFormColumn++) {
                            MergeRegionRangePojo subMergeRegionRangePojo = ExcelUtil.isMergedRegion(sheet, subTitleRow.getRowNum(), subFormColumn);
                            boolean subSingleRowSubForm = ! subMergeRegionRangePojo.getIsMergedCell();
                            boolean subMultiRowSubForm = subMergeRegionRangePojo.getIsMergedCell() && !Objects.equals(subMergeRegionRangePojo.getFirstColumn(), subMergeRegionRangePojo.getLastColumn());
                            if (subTitleRow.getCell(subFormColumn) == null) {
                                titleColumnIndex ++;
                                break;
                            }
                            subTitle = subTitleRow.getCell(subFormColumn).getStringCellValue();
                            hasSubMark = subTitle.indexOf(ImportConstant.TITLE_CAN_IMPORT_SEPARATELY) != -1;
                            if (subSingleRowSubForm || subMultiRowSubForm || hasSubMark) {
                                Row subSubTitleRow = tempSheet.getRow(titleRowIndex + 2);
                                for (int subSubFormColumn = subMergeRegionRangePojo.getFirstColumn(); subSubFormColumn <= subMergeRegionRangePojo.getLastColumn(); subSubFormColumn ++) {
                                    MergeRegionRangePojo subMergeRegionRangePojo1 = ExcelUtil.isMergedRegion(sheet, subSubTitleRow.getRowNum(), subSubFormColumn);
                                    boolean subSingleRowSubForm1 = ! subMergeRegionRangePojo1.getIsMergedCell();
                                    boolean subMultiRowSubForm1 = subMergeRegionRangePojo1.getIsMergedCell() && !Objects.equals(subMergeRegionRangePojo1.getFirstColumn(), subMergeRegionRangePojo1.getLastColumn());
                                    if (subSubTitleRow.getCell(subSubFormColumn) == null) {
                                        titleColumnIndex ++;
                                        break;
                                    }
                                    subSubTitle = subSubTitleRow.getCell(subSubFormColumn).getStringCellValue();
                                    hasSubMark = subSubTitle.indexOf(ImportConstant.TITLE_CAN_IMPORT_SEPARATELY) != -1;
                                    if (subSingleRowSubForm1 || subMultiRowSubForm1 || hasSubMark) {
                                        Row subSubTitleRow1 = tempSheet.getRow(titleRowIndex + 3);
                                        for (int subSubFormColumn1 = subMergeRegionRangePojo1.getFirstColumn(); subSubFormColumn1 <= subMergeRegionRangePojo1.getLastColumn(); subSubFormColumn1 ++) {
                                            subSubSubTitle = subSubTitleRow1.getCell(subSubFormColumn1).getStringCellValue();
                                            CellTitlePojo titlePojo = new CellTitlePojo(subSubSubTitle, subSubTitle, subTitle, title, titleColumnIndex);
                                            titleList.add(titlePojo);
                                            titleColumnIndex++;
                                            if (subSubFormColumn1 < subMergeRegionRangePojo1.getLastColumn()) {
                                                subFormColumn ++;
                                                subSubFormColumn ++;
                                            }
                                        }
                                    } else {
                                        CellTitlePojo titlePojo = new CellTitlePojo(subSubTitle, subTitle, title, titleColumnIndex);
                                        titleList.add(titlePojo);
                                        titleColumnIndex++;
                                        if (subSubFormColumn < subMergeRegionRangePojo.getLastColumn()) {
                                            subFormColumn ++;
                                        }
                                    }
                                }
                            } else {
                                CellTitlePojo titlePojo = new CellTitlePojo(subTitle, title, titleColumnIndex);
                                titleList.add(titlePojo);
                                titleColumnIndex++;
                            }
                        }
                    } else {
                        CellTitlePojo titlePojo = new CellTitlePojo(title, titleColumnIndex);
                        titleList.add(titlePojo);
                        titleColumnIndex++;
                    }
                } else {
                    CellTitlePojo titlePojo = new CellTitlePojo(title, titleColumnIndex);
                    titleList.add(titlePojo);
                    titleColumnIndex++;
                }
            }
        } catch (Exception e) {
            LOG.error("handleImportServiceImpl.getExcelTitle执行出错", e);
            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235002);
        }

        return titleList;
    }

    @Override
    public  String[][] getExcelValue(Workbook workBook, int rowIndex) throws XbbException{
        String[][] excelDataArray;
        try {
            Sheet sheet = workBook.getSheetAt(0);
            // 获取行数
            int rowNum = sheet.getLastRowNum() + 1;
            // 获取列数
            int columnNum = sheet.getRow(rowIndex).getLastCellNum();
            excelDataArray = new String[rowNum][columnNum];
            // 遍历行
            for (int i = 0; i < rowNum; i++) {
                // 读取左上端单元格
                Row row = sheet.getRow(i);
                if (row != null) {
                    excelDataArray[i] = ExcelUtil.getExcelRowValue(row, columnNum);
                }
            }
        } catch (Exception e) {
            LOG.error("读取Excel数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return excelDataArray;
    }


    @Override
    public List<RowGroupPojo> handleDiscount( List<RowGroupPojo> rowGroupPojoList, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        try {
            //管理中心存在修改标题的情况，故取解释的attrName
            String discoutName = "";
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                if (Objects.equals(fieldAttrEntityForImport.getSaasAttr(), QuotationEnum.DISCOUNT.getSaasAttr())) {
                    discoutName = fieldAttrEntityForImport.getAttrName();
                }
            }
            for (RowGroupPojo rowGroupPojo : rowGroupPojoList) {
                List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
                // 分组的第一条数据作为给实体对象赋值的数据
                List<CellValuePojo> cellValueList = rowValueList.get(0);
                //获取整单折扣若是百分比转换成小数
                for (CellValuePojo cellValuePojo : cellValueList) {
                    if (Objects.equals(cellValuePojo.getTitle(), discoutName + "*") || Objects.equals(cellValuePojo.getTitle(), discoutName)) {
                        Object value = cellValuePojo.getValue();
                        String discount = Objects.toString(value, "");
                        if (!Objects.equals(discount, "")) {
                            String s = discount.substring(discount.length()-1,discount.length());
                            Double num;
                            if (Objects.equals(s, "%")) {
                                discount = discount.substring(0,discount.length() - 1);
                                Double num1 = Double.parseDouble(discount) / 100;
                                discount = num1.toString();
                                //整单折扣要求是(0,1)的两位小数
                                if (Objects.equals(discount, "0") || Objects.equals(discount, "1") || Objects.equals(discount, "1.0") || Objects.equals(discount, "0.0")) {
                                    num = Double.parseDouble(discount);
                                } else {
                                    if (!discount.matches(RegExConstant.DISCOUNT)) {
                                        throw new XbbException(QuotationErrorCodeEnum.API_ERROR_246011);
                                    }
                                    num = Double.parseDouble(discount);
                                }
                            } else {
                                //整单折扣要求是(0,1)的两位小数
                                if (Objects.equals(discount, "0") || Objects.equals(discount, "1")) {
                                    num = Double.parseDouble(discount);
                                } else {
                                    if (!discount.matches(RegExConstant.DISCOUNT)) {
                                        throw new XbbException(QuotationErrorCodeEnum.API_ERROR_246011);
                                    }
                                    num = Double.parseDouble(discount);
                                }
                            }
                            cellValuePojo.setValue(num);
                        }
                    }
                }
            }
            return rowGroupPojoList;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("ExcelOperatorService导入数据，处理整单折扣出错", e);
            throw new XbbException(QuotationErrorCodeEnum.API_ERROR_246006);
        }
    }

    @Override
    public UniqueIndexPojo getUniqueIdentityColumnIndex(Integer businessType, List<FieldAttrEntityForImport> fieldAttrList, List<CellTitlePojo> titlePojoList) {
        UniqueIndexPojo uniqueIndexPojo = new UniqueIndexPojo();
        // 数据的唯一标识符字段 一般是serialNo
        String attr = FieldTypeEnum.SERIALNO.getAlias();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
            case DISTRIBUTOR_MANAGEMENT:
                Integer customerNameRepeat = 0;
                FieldAttrEntity customerPhoneRepeat = null;
                attr = null;
                List<String> noRepeatAttrList = new ArrayList<>();
                for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntityForImport.getNoRepeat(), 1)) {
                        noRepeatAttrList.add(fieldAttrEntityForImport.getAttr());
                    }
                    if (Objects.equals(fieldAttrEntityForImport.getAttr(), CustomerManagementEnum.NAME.getAttr())) {
                        customerNameRepeat = fieldAttrEntityForImport.getNoRepeat();
                    }
                    if (Objects.equals(fieldAttrEntityForImport.getAttr(), CustomerManagementEnum.PHONE.getAttr())) {
                        SubFormPoJo subForm = fieldAttrEntityForImport.getSubForm();
                        if (!Objects.isNull(subForm)) {
                            for (FieldAttrEntity item : subForm.getItems()) {
                                if (Objects.equals(item.getNoRepeat(), BasicConstant.ONE)) {
                                    noRepeatAttrList.add(fieldAttrEntityForImport.getAttr() + StringConstant.POINT + item.getAttr());
                                }
                            }
                        }
                    }
                }
                /**
                 * 1.客户名称、电话判重都关闭，默认每一行都是唯一的客户数据；自定义字段判重、根据自定义字段进行子表单合并；
                 * 2.客户名称判重，采用客户名称判重
                 */
                if (Objects.equals(customerNameRepeat, 0) && CollectionUtils.isNotEmpty(noRepeatAttrList)) {
                    attr = noRepeatAttrList.get(0);
                }  else if (Objects.equals(customerNameRepeat, 1)) {
                    attr = CustomerManagementEnum.NAME.getAttr();
                }
                break;
            case CLUE:
                Integer clueNameRepeat = 0;
                attr = null;
                List<String> noRepeatAttrs = new ArrayList<>();
                for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                    if (Objects.equals(fieldAttrEntityForImport.getNoRepeat(), 1)) {
                        noRepeatAttrs.add(fieldAttrEntityForImport.getAttr());
                    }
                    if (Objects.equals(fieldAttrEntityForImport.getAttr(), ClueEnum.COMPANY_NAME.getAttr())) {
                        clueNameRepeat = fieldAttrEntityForImport.getNoRepeat();
                    }
                }
                /**
                 * 1.线索名称、电话判重都关闭，默认每一行都是唯一的线索数据；自定义字段判重、根据自定义字段进行子表单合并；
                 * 2.线索名称判重，采用线索名称判重
                 */
                if (Objects.equals(clueNameRepeat, 0) && CollectionUtils.isNotEmpty(noRepeatAttrs)) {
                    attr = noRepeatAttrs.get(0);
                }  else if (Objects.equals(clueNameRepeat, 1)) {
                    attr = ClueEnum.COMPANY_NAME.getAttr();
                }
                break;
            case SUPPLIER:
                attr = SupplierEnum.SUPPLIER_NAME.getAttr();
                break;
            case CONTACT:
            case DISTRIBUTOR_CONTACT:
                attr = ContactEnum.NAME.getAttr();
                break;
            case DISTRIBUTOR_ACCOUNT:
                attr = DistributorAccountEnum.NAME.getAttr();
                break;
            case PRODUCT:
                attr = ProductEnum.SERIALNO.getAttr();
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                attr = InstockEnum.SHEET_NO.getAttr();
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                attr = OutstockEnum.SHEET_NO.getAttr();
                break;
            case SUPPLIER_CONTACT:
                attr = SupplierContactEnum.NAME.getAttr();
                break;
            case PURCHASE:
                attr = PurchaseEnum.SHEET_NO.getAttr();
                break;
            case RETURNED_PURCHASE:
                attr = ReturnedPurchaseEnum.SHEET_NO.getAttr();
                break;
            case ORI_STOCK:
                attr = OriStockEnum.ORI_STOCK_NO.getAttr();
                break;
            case PAYMENT_SHEET:
                attr = PaymentSheetEnum.SHEET_NO.getAttr();
                break;
            case PAY_SHEET:
                attr = PaySheetEnum.PAY_PLAN_NO.getAttr();
                break;
            case PAYMENT:
                attr = PaymentEnum.PAYMENT_NO.getAttr();
                break;
            case PRICE_SET_PRODUCT:
                attr = PriceSetEnum.NAME.getAttr();
                break;
            default:
                break;
        }

        if (Objects.nonNull(attr)) {
            Integer index;
            if (attr.contains(StringConstant.POINT)) {
                String[] split = attr.split("\\.");
                // 子表单情况
                String attrName = importHelper.getAttrNameFromExplainByAttr(fieldAttrList, attr);
                String attrParentName = importHelper.getAttrNameFromExplainByAttr(fieldAttrList, split[0]);
                index = importHelper.getColumnIndexByTitle(titlePojoList, attrName, attrParentName);
            } else {
                String attrName = importHelper.getAttrNameFromExplainByAttr(fieldAttrList, attr);
                index = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            }
            uniqueIndexPojo.setIndex(index);
        }
        uniqueIndexPojo.setAttr(attr);
        return uniqueIndexPojo;
    }

    @Override
    public List<Integer> getQuotationIdentityColumnIndex(List<FieldAttrEntityForImport> fieldAttrList, List<CellTitlePojo> titlePojoList) {
        List<Integer> ColumnList = new LinkedList<>();
        String groupNumberAttr = QuotationEnum.GROUP_NUMBER.getAttr();
        String versionAttr = QuotationEnum.VERSION.getAttr();
        String groupNumberAttrName = importHelper.getAttrNameFromExplainByAttr(fieldAttrList, groupNumberAttr);
        String versionAttrName = importHelper.getAttrNameFromExplainByAttr(fieldAttrList, versionAttr);
        Integer ColumnGroupNumber = importHelper.getColumnIndexByTitle(titlePojoList, groupNumberAttrName, null);
        ColumnList.add(ColumnGroupNumber);
        Integer ColumnVersion = importHelper.getColumnIndexByTitle(titlePojoList, versionAttrName, null);
        ColumnList.add(ColumnVersion);
        return ColumnList;

    }

    @Override
    public void  filterUnImportFields(List<FieldAttrEntityForImport> fieldAttrList, Integer saasMark, Integer fromImport, Integer businessType, String corpid, Long formId,Integer isFileImport) throws XbbException {
        boolean formShareTag = userTeamHelp.getFormShareTag(corpid, formId, businessType);
        List<Integer> unnecessaryFieldType = Arrays.asList(FieldTypeEnum.SEPARATOR.getType(), FieldTypeEnum.MEMO.getType(),
                FieldTypeEnum.VIDEO.getType(), FieldTypeEnum.LINK_QUERY.getType(), FieldTypeEnum.RICH_TEXT_EDITOR.getType(),
                FieldTypeEnum.FIRST_INTO_STAGE_TIME.getType(), FieldTypeEnum.NOW_INTO_STAGE_TIME.getType(),
                FieldTypeEnum.RICH_TEXT.getType(),FieldTypeEnum.MANUAL_SIGN.getType(),FieldTypeEnum.RICH_TEXT.getType(),FieldTypeEnum.TEMPLATE_FIELD.getType());
        boolean importWhiteCorpidList = fileImportExportHelp.isWhiteListByCorpidAndType(corpid, "importWhiteCorpidList");
        // 不在导入白名单或者没有选择带附件导入，则过滤图片与附件
        if (!importWhiteCorpidList || !Objects.equals(isFileImport, 1)) {
            unnecessaryFieldType = new ArrayList<>(unnecessaryFieldType);
            unnecessaryFieldType.add(FieldTypeEnum.IMAGE.getType());
            unnecessaryFieldType.add(FieldTypeEnum.UPLOAD.getType());
        }
        // 来自于导入的过滤掉创建时间，更新时间，创建人
        if (Objects.equals(fromImport, ImportConstant.FROM_IMPORT)) {
            unnecessaryFieldType = new ArrayList<>(unnecessaryFieldType);
            unnecessaryFieldType.add(FieldTypeEnum.ADDTIME.getType());
            unnecessaryFieldType.add(FieldTypeEnum.UPDATETIME.getType());
            unnecessaryFieldType.add(FieldTypeEnum.LOCATION.getType());
        }
        Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = iterator.next();
            boolean unnecessaryField = (Objects.equals(fieldAttrEntity.getIsRedundant(), 1) && (Objects.equals(fieldAttrEntity.getVisible(), 0)) || Objects.equals(fieldAttrEntity.getIsOpen(), 2))
                    || (Objects.equals(fieldAttrEntity.getIsRedundant(), 0) && (Objects.equals(fieldAttrEntity.getIsOpen(), 0) || Objects.equals(fieldAttrEntity.getIsOpen(), 2)|| Objects.equals(fieldAttrEntity.getVisible(), 0)))
                    || unnecessaryFieldType.contains(fieldAttrEntity.getFieldType());
            if (unnecessaryField) {
                iterator.remove();
            } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType())) {
                List<? extends FieldAttrEntity> subFieldAttrList = fieldAttrEntity.getSubForm().getItems();
                Iterator<? extends FieldAttrEntity> subIterator = subFieldAttrList.iterator();
                while (subIterator.hasNext()) {
                    FieldAttrEntity subFieldAttrEntity = subIterator.next();
                    // 关联产品里面的自带产品名称关联数据不过滤，李杰哥哥说的
                    if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SELECT_PRODUCT.getType()) && Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.PRODUCT.getAttr())) {
                        continue;
                    }
                    boolean unnecessarySubField =(Objects.equals(subFieldAttrEntity.getIsRedundant(), 1) && (Objects.equals(subFieldAttrEntity.getVisible(), 0) || Objects.equals(subFieldAttrEntity.getIsOpen(), 2)))
                            || (Objects.equals(subFieldAttrEntity.getIsRedundant(), 0) && (Objects.equals(subFieldAttrEntity.getIsOpen(), 0) || Objects.equals(subFieldAttrEntity.getIsOpen(), 2) || Objects.equals(subFieldAttrEntity.getVisible(), 0)))
                            || unnecessaryFieldType.contains(subFieldAttrEntity.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subFieldAttrEntity.getFieldType())
                            || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), subFieldAttrEntity.getFieldType()) && !Objects.equals(ManagementBaseEnum.ADD_CONTACT.getAttr(), fieldAttrEntity.getAttr());
                    //关联新建 例如客户-联系人 开放关联数据字段导入
                    if (unnecessarySubField) {
                        subIterator.remove();
                    }
                }
                fieldAttrEntity.getSubForm().setItems(subFieldAttrList);
            } else if ( (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())  && Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.ADD_PAYMENT.getAttr()))
                    || (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode()) &&  Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.ADD_PAYPLAN.getAttr()))
                    || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_FORM_BUTTON.getType())
                    || (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()) && (Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.TOTAL_MONEY.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ContractOutstockEnum.PRODUCT_TOTAL.getAttr())))){
                iterator.remove();
            }  else if(Objects.equals(businessType,XbbRefTypeEnum.SUPPLIER.getCode()) && Objects.equals(fieldAttrEntity.getAttr(),SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr())){
                iterator.remove();
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.RECEIVABLE_PERIOD.getAttr())) {
                    iterator.remove();
                }else if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.COUSERID.getAttr()) && !formShareTag) {
                    iterator.remove();
                }
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) && Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.RECEIVABLE_PERIOD.getAttr())) {
                iterator.remove();
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_LIMIT.getCode()) && (Objects.equals(fieldAttrEntity.getAttr(), CreditLimitEnum.TEMPORARY_LIMIT.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), CreditLimitEnum.USED_LIMIT.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), CreditLimitEnum.AVAILABLE_LIMIT.getAttr()))) {
                iterator.remove();
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode()) && (Objects.equals(fieldAttrEntity.getAttr(), CreditTemporaryLimitEnum.APPLY_ID.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), CreditTemporaryLimitEnum.APPLY_TIME.getAttr()))) {
                iterator.remove();
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode()) && (Objects.equals(fieldAttrEntity.getAttr(), CreditFixedLimitEnum.APPLY_ID.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), CreditFixedLimitEnum.APPLY_TIME.getAttr()))) {
                iterator.remove();
            }else if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT.getCode()) && (Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.RED_AMOUNT.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.GENERATION_DATE.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.SOURCE.getAttr()))) {
                iterator.remove();
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.COUSERID.getAttr()) && !formShareTag) {
                    iterator.remove();
                }
            }else if (Objects.equals(businessType, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
                List<String> attrList= KnowledgeDataEnum.getNotImportAttrList(XbbRefTypeEnum.KNOWLEDGE_BASE.getCode());
                if (attrList.contains(fieldAttrEntity.getAttr())) {
                    iterator.remove();
                }
            }
        }
    }

    @Override
    public void filterUnExportFields(String corpid, List<FieldAttrEntityForImport> fieldAttrList, Integer saasMark, Integer fromImport, Integer businessType, Boolean partialExportFlag) throws XbbException {
        // 导出过滤的字段
        List<Integer> unnecessaryFieldType = Arrays.asList(FieldTypeEnum.SEPARATOR.getType(), FieldTypeEnum.MEMO.getType(),
                FieldTypeEnum.VIDEO.getType(), FieldTypeEnum.LINK_QUERY.getType() , FieldTypeEnum.RICH_TEXT_EDITOR.getType(),
                FieldTypeEnum.FIRST_INTO_STAGE_TIME.getType(), FieldTypeEnum.NOW_INTO_STAGE_TIME.getType(),
                FieldTypeEnum.RICH_TEXT.getType(),FieldTypeEnum.MANUAL_SIGN.getType());
        if (!partialExportFlag) {
            unnecessaryFieldType = new ArrayList<>(unnecessaryFieldType);
            unnecessaryFieldType.add(FieldTypeEnum.IMAGE.getType());
            unnecessaryFieldType.add(FieldTypeEnum.UPLOAD.getType());
        }
        if(!partialExportFlag){
            unnecessaryFieldType.add(FieldTypeEnum.TEMPLATE_FIELD.getType());
        }
        // 来自于导出的过滤掉创建时间，更新时间，创建人
        if (Objects.equals(fromImport, ImportConstant.FROM_IMPORT)) {
            unnecessaryFieldType = new ArrayList<>(unnecessaryFieldType);
            unnecessaryFieldType.add(FieldTypeEnum.ADDTIME.getType());
            unnecessaryFieldType.add(FieldTypeEnum.UPDATETIME.getType());
            unnecessaryFieldType.add(FieldTypeEnum.LOCATION.getType());
            unnecessaryFieldType.add(FieldTypeEnum.TEMPLATE_FIELD.getType());
        }
        Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = iterator.next();
            boolean unnecessaryField = (Objects.equals(fieldAttrEntity.getIsRedundant(), 1) && (Objects.equals(fieldAttrEntity.getVisible(), 0) || Objects.equals(fieldAttrEntity.getIsOpen(), 2)))
                    || (Objects.equals(fieldAttrEntity.getIsRedundant(), 0) && (Objects.equals(fieldAttrEntity.getIsOpen(), 0) || Objects.equals(fieldAttrEntity.getVisible(), 0)))
                    || (Objects.equals(fieldAttrEntity.getIsRedundant(), 1) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType()) && (Objects.equals(fieldAttrEntity.getIsOpen(), 0) || Objects.equals(fieldAttrEntity.getVisible(), 0)))
                    || unnecessaryFieldType.contains(fieldAttrEntity.getFieldType());
            if (unnecessaryField) {
                iterator.remove();
            } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())) {
                List<? extends FieldAttrEntity> subFieldAttrList = fieldAttrEntity.getSubForm().getItems();
                Iterator<? extends FieldAttrEntity> subIterator = subFieldAttrList.iterator();
                while (subIterator.hasNext()) {
                    FieldAttrEntity subFieldAttrEntity = subIterator.next();
                    boolean unnecessarySubField =(Objects.equals(subFieldAttrEntity.getIsRedundant(), 1) && (Objects.equals(subFieldAttrEntity.getVisible(), 0) || Objects.equals(subFieldAttrEntity.getIsOpen(), 2)))
                            || (Objects.equals(subFieldAttrEntity.getIsRedundant(), 0) && (Objects.equals(subFieldAttrEntity.getIsOpen(), 0) || Objects.equals(subFieldAttrEntity.getVisible(), 0)))
                            || unnecessaryFieldType.contains(subFieldAttrEntity.getFieldType());
                    if (unnecessarySubField) {
                        subIterator.remove();
                    }
                }
                fieldAttrEntity.getSubForm().setItems(subFieldAttrList);
            } else if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SELECT_SERVICE.getType())) {
                List<? extends FieldAttrEntity> subFieldAttrList = fieldAttrEntity.getSubForm().getItems();
                Iterator<? extends FieldAttrEntity> subIterator = subFieldAttrList.iterator();
                while (subIterator.hasNext()) {
                    FieldAttrEntity subFieldAttrEntity = subIterator.next();
                    boolean unnecessarySubField =(Objects.equals(subFieldAttrEntity.getIsRedundant(), 1) && (Objects.equals(subFieldAttrEntity.getVisible(), 0) || Objects.equals(subFieldAttrEntity.getIsOpen(), 2)))
                            || (Objects.equals(subFieldAttrEntity.getIsRedundant(), 0) && (Objects.equals(subFieldAttrEntity.getIsOpen(), 0) || Objects.equals(subFieldAttrEntity.getVisible(), 0)))
                            || unnecessaryFieldType.contains(subFieldAttrEntity.getFieldType());
                    if (unnecessarySubField) {
                        subIterator.remove();
                    }
                }
                fieldAttrEntity.getSubForm().setItems(subFieldAttrList);
            }
            else if ((Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())  && Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.ADD_PAYMENT.getAttr()))
                    || (Objects.equals(businessType, XbbRefTypeEnum.ORDER.getCode())  && Objects.equals(fieldAttrEntity.getAttr(), OrderEnum.ADD_PAYMENT.getAttr()))
                    || (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode()) &&  Objects.equals(fieldAttrEntity.getAttr(), PurchaseEnum.ADD_PAYPLAN.getAttr()))
                    || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_FORM_BUTTON.getType())){
                iterator.remove();
            } else if(Objects.equals(businessType,XbbRefTypeEnum.SUPPLIER.getCode()) && Objects.equals(fieldAttrEntity.getAttr(),SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr())){
                iterator.remove();
            }
        }
    }


    @Override
    public void waitSeriesFields(List<FieldAttrEntityForImport> fieldAttrList, FormDataListDTO formDataListDTO ) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getSubBusinessType(), formDataListDTO.getDistributorMark()));
        switch (xbbRefTypeEnum) {
            case WAIT_INSTOCK_PURCHASE:
                if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE.getCode())){
                    fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(fieldAttrEntityForImport.getAttr(),"option_8") || Objects.equals(fieldAttrEntityForImport.getAttr(),"option_0"));
                    //封装待入库产品子表单解释
                    PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),formDataListDTO.getCorpid());
                    if (paasFormExplainEntity == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                    }
                    SubFormPoJo subForm = setWaitInstockProductFormExplain(paasFormExplainEntity);
                    //封装待入库产品解释
                    PaasFormExplainEntity paasFormExplainEnt = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.INVENTORY.getCode(), formDataListDTO.getCorpid());
                    List<FieldAttrEntityForImport> explains = JSON.parseArray(paasFormExplainEnt.getExplains(), FieldAttrEntityForImport.class);
                    for (FieldAttrEntityForImport fieldAttrEntity : explains) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), InventoryEnum.PRODUCT.getAttr())) {
                            fieldAttrEntity.setAttrName("待入库产品");
                            fieldAttrEntity.setSubForm(subForm);
                            fieldAttrList.add(fieldAttrEntity);
                            break;
                        }
                    }
                }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){

                    fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(fieldAttrEntityForImport.getAttr(),"option_0"));
                }
                break;
            case SMART_REPLENISHMENT:
                Iterator<FieldAttrEntityForImport> iterators = fieldAttrList.iterator();
                while (iterators.hasNext()) {
                    FieldAttrEntityForImport fieldAttrEntity = iterators.next();
                    String attr = fieldAttrEntity.getAttr();
                    if (Objects.equals(attr,"option_0")){
                        iterators.remove();
                    }
                    if (Objects.equals(attr,ContractEnum.LINK_CUSTOMER.getAttr())){
                        fieldAttrEntity.setLinkedType(FieldTypeEnum.TEXT.getType());
                    }
                }
                break;
            case WAIT_PURCHASE:
                if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
                    Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
                    while (iterator.hasNext()) {
                        FieldAttrEntityForImport fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (Objects.equals(attr,"option_0")
                                || Objects.equals(attr,"option_5")){
                            iterator.remove();
                        }
                        if (Objects.equals(attr,ContractEnum.LINK_CUSTOMER.getAttr())){
                            fieldAttrEntity.setLinkedType(FieldTypeEnum.TEXT.getType());
                        }
                    }
                    //封装以销代购产品子表单解释
                    SubFormPoJo subForm = setWaitPurchaseProductFormExplain(formDataListDTO);
                    //封装待入库产品解释
                    PaasFormExplainEntity paasFormExplainEnt = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.INVENTORY.getCode(), formDataListDTO.getCorpid());
                    List<FieldAttrEntityForImport> explains = JSON.parseArray(paasFormExplainEnt.getExplains(), FieldAttrEntityForImport.class);
                    for (FieldAttrEntityForImport fieldAttrEntity : explains) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), InventoryEnum.PRODUCT.getAttr())) {
                            fieldAttrEntity.setAttr("array_2");
                            fieldAttrEntity.setAttrName("待采购产品");
                            fieldAttrEntity.setSubForm(subForm);
                            fieldAttrList.add(fieldAttrEntity);
                            break;
                        }
                    }
                }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                    Iterator<FieldAttrEntityForImport> iterator = fieldAttrList.iterator();
                    while (iterator.hasNext()) {
                        FieldAttrEntityForImport fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if (Objects.equals(attr,"option_0")
                                || Objects.equals(attr,"purchaseDetail")
                                || Objects.equals(attr,"stockSearch")){
                            iterator.remove();
                        }
                        if (Objects.equals(attr,ContractEnum.LINK_CUSTOMER.getAttr())){
                            fieldAttrEntity.setLinkedType(FieldTypeEnum.TEXT.getType());
                        }
                    }
                }
                break;
            case WAIT_OUTSTOCK:
                if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
                    fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(fieldAttrEntityForImport.getAttr(),"option_9") || Objects.equals(fieldAttrEntityForImport.getAttr(),"option_0"));
                    //封装待出库产品子表单解释
                    PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),formDataListDTO.getCorpid());
                    if (paasFormExplainEntity == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                    }
                    SubFormPoJo subForm = setWaitOutstockProductFormExplain(paasFormExplainEntity);
                    //封装待出库产品解释
                    PaasFormExplainEntity paasFormExplainEnt = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTRACT.getCode(), formDataListDTO.getCorpid());
                    List<FieldAttrEntityForImport> explains = JSON.parseArray(paasFormExplainEnt.getExplains(), FieldAttrEntityForImport.class);
                    for (FieldAttrEntityForImport fieldAttrEntity : explains) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.PRODUCT.getAttr())) {
                            fieldAttrEntity.setAttrName("待出库产品");
                            fieldAttrEntity.setSubForm(subForm);
                            fieldAttrList.add(fieldAttrEntity);
                            break;
                        }
                    }
                    for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.LINK_CUSTOMER.getAttr())) {
                            fieldAttrEntity.setLinkedType(FieldTypeEnum.TEXT.getType());
                            break;
                        }
                    }
                }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                    for (FieldAttrEntityForImport fieldAttrEntity : fieldAttrList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.LINK_CUSTOMER.getAttr())) {
                            fieldAttrEntity.setLinkedType(FieldTypeEnum.TEXT.getType());
                            break;
                        }
                    }
                    FieldAttrEntityForImport waitOutStockField = new FieldAttrEntityForImport();
                        waitOutStockField.setAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttr());
                        waitOutStockField.setAttrName(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName());
                        waitOutStockField.setFieldType(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getFieldType());
                        waitOutStockField.setSaasAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getSaasAttr());
                        waitOutStockField.setLinkedType(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getLinkedType());
                        waitOutStockField.setDisableListSort(0);
                        waitOutStockField.setIsRedundant(1);
                    fieldAttrList.add(waitOutStockField);
                    fieldAttrList.removeIf(fieldAttrEntityForImport -> Objects.equals(fieldAttrEntityForImport.getAttr(),"option_0"));
                }
                break;
            default:
                break;
        }
    }

    private SubFormPoJo setWaitInstockProductFormExplain(PaasFormExplainEntity paasFormExplainEntity){
        SubFormPoJo subForm = new SubFormPoJo();
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Iterator<FieldAttrEntity> iterator = explainList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = iterator.next();
            String attr = fieldAttrEntity.getAttr();
            if (!( Objects.equals(attr, ProductEnum.NAME.getAttr())
                    || Objects.equals(attr, ProductEnum.SERIALNO.getAttr())
                    || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                    || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                    || Objects.equals(attr, ProductEnum.STOCK.getAttr()))) {
                iterator.remove();
            }
            fieldAttrEntity.setEditable(0);
        }
        for (FieldAttrEntity fieldAttrEntity:explainList){
            if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SERIALNO.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.PRODUCT_NO.getAttr());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.NAME.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.PRODUCT_NAME.getAttr());
                fieldAttrEntity.setAttrName(WaitOutstockEnum.PRODUCT_NAME.getAttrName());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.SPECIFICATION.getAttr());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.UNIT.getAttr())){
                fieldAttrEntity.setAttrName(WaitOutstockEnum.UNIT.getAttrName());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.STOCK.getAttr())){
                fieldAttrEntity.setAttrName(WaitOutstockEnum.STOCK.getAttrName());
                fieldAttrEntity.setIsRedundant(1);
            }
        }
        FieldAttrEntity memoField = new FieldAttrEntity();
        memoField.setAttr(WaitOutstockEnum.MEMO.getAttr());
        memoField.setAttrName(WaitOutstockEnum.MEMO.getAttrName());
        memoField.setFieldType(WaitOutstockEnum.MEMO.getFieldType());
        memoField.setSaasAttr(WaitOutstockEnum.MEMO.getSaasAttr());
        memoField.setLinkedType(WaitOutstockEnum.MEMO.getLinkedType());
        memoField.setDisableListSort(0);
        memoField.setIsRedundant(1);
        explainList.add(memoField);
        subForm.setItems(explainList);
        return subForm;
    }

    private SubFormPoJo setWaitPurchaseProductFormExplain(FormDataListDTO formDataListDTO){
        SubFormPoJo subForm = new SubFormPoJo();
        String locale = formDataListDTO.getLocale();
        boolean isEnglish = false;
        if (Objects.equals(locale,"en_US")){
            isEnglish = true;
        }
        List<FieldAttrEntity> headList = saasListService.handleWaitProductHead(false,isEnglish);
        headList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.PRODUCT_IMGS.getSaasAttr())
                || Objects.equals(fieldAttrEntity.getAttr(),"purchaseDetail")
                || Objects.equals(fieldAttrEntity.getAttr(),"stockSearch"));
        subForm.setItems(headList);
        return subForm;
    }

    private SubFormPoJo setWaitOutstockProductFormExplain(PaasFormExplainEntity paasFormExplainEntity){
        SubFormPoJo subForm = new SubFormPoJo();
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Iterator<FieldAttrEntity> iterator = explainList.iterator();
        while (iterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = iterator.next();
            String attr = fieldAttrEntity.getAttr();
            if (!( Objects.equals(attr, ProductEnum.NAME.getAttr())
                    || Objects.equals(attr, ProductEnum.SERIALNO.getAttr())
                    || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                    || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                    || Objects.equals(attr, ProductEnum.STOCK.getAttr()))) {
                iterator.remove();
            }
            fieldAttrEntity.setEditable(0);
        }
        for (FieldAttrEntity fieldAttrEntity:explainList){
            if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SERIALNO.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.PRODUCT_NO.getAttr());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.NAME.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.PRODUCT_NAME.getAttr());
                fieldAttrEntity.setAttrName(WaitOutstockEnum.PRODUCT_NAME.getAttrName());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.SPECIFICATION.getAttr());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.UNIT.getAttr())){
                fieldAttrEntity.setAttrName(WaitOutstockEnum.UNIT.getAttrName());
                fieldAttrEntity.setIsRedundant(1);
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.STOCK.getAttr())){
                fieldAttrEntity.setAttrName(WaitOutstockEnum.STOCK.getAttrName());
                fieldAttrEntity.setIsRedundant(1);
            }
        }
        FieldAttrEntity waitNumField = new FieldAttrEntity();
        waitNumField.setAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttr());
        waitNumField.setAttrName(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName());
        waitNumField.setFieldType(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getFieldType());
        waitNumField.setSaasAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getSaasAttr());
        waitNumField.setLinkedType(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getLinkedType());
        waitNumField.setDisableListSort(0);
        waitNumField.setIsRedundant(1);
        explainList.add(waitNumField);
        subForm.setItems(explainList);
        FieldAttrEntity memoField = new FieldAttrEntity();
        memoField.setAttr(WaitOutstockEnum.MEMO.getAttr());
        memoField.setAttrName(WaitOutstockEnum.MEMO.getAttrName());
        memoField.setFieldType(WaitOutstockEnum.MEMO.getFieldType());
        memoField.setSaasAttr(WaitOutstockEnum.MEMO.getSaasAttr());
        memoField.setLinkedType(WaitOutstockEnum.MEMO.getLinkedType());
        memoField.setDisableListSort(0);
        memoField.setIsRedundant(1);
        explainList.add(memoField);
        return subForm;
    }

    @Override
    public void handleLinkForm(LinkFormImportPojo linkFormImportPojo, Integer distributorMark) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(linkFormImportPojo.getBusinessType());
        List<FieldAttrEntityForImport> fieldAttrList = linkFormImportPojo.getFieldAttrEntityForImportList();
        LinkFormItemDTO linkFormItemDTO = new LinkFormItemDTO();
        linkFormItemDTO.setDistributorMark(distributorMark);
        BeanUtil.copyProperties(linkFormImportPojo, linkFormItemDTO);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
            case DISTRIBUTOR_MANAGEMENT:
                linkFormItemDTO.setLinkBusinessType(RedundantTemplateTypeEnum.CONTACT.getCode());
                break;
//            case CONTRACT:
//                linkFormItemDTO.setLinkBusinessType(RedundantTemplateTypeEnum.PAYMENT.getCode());
//                break;
//            case PURCHASE:
//                linkFormItemDTO.setLinkBusinessType(RedundantTemplateTypeEnum.PAY_PLAN.getCode());
//                break;
            default:
                break;
        }
        if (Objects.nonNull(linkFormItemDTO.getLinkBusinessType())) {
            LinkFormItemVO linkFormItemVO = paasFormExplainService.linkFormList(linkFormItemDTO);
            FieldAttrEntityForImport linkFormField = new FieldAttrEntityForImport();
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.LINK_FORM.getType())) {
                    linkFormField = fieldAttrEntityForImport;
                    break;
                }
            }
            List<FieldAttrEntity> explainList = linkFormItemVO.getExplainList();
//            Integer formImportOrExport = linkFormImportPojo.getFormImportOrExport();
//            List<String> noImportAttr;
//            switch (redundantTemplateTypeEnum) {
//                case PURCHASE:
//                    noImportAttr = Arrays.asList(PayPlanEnum.REAL_AMOUNT.getAttr(), PayPlanEnum.UN_AMOUNT.getAttr());
//                    explainList.removeIf(explain -> Objects.equals(formImportOrExport, ImportConstant.FROM_IMPORT) && noImportAttr.contains(explain.getAttr()));
//                    explainList.removeIf(explain-> Objects.equals(explain.getAttr(), PayPlanEnum.BELONGER.getAttr())
//                    || Objects.equals(explain.getAttr(), PayPlanEnum.PAYMENT_METHOD.getAttr()));
//                    List<String> canImportStatusList = Arrays.asList(PayPlanStatusEnum.RECEIVABLES.getCode(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());
//                    explainList.forEach(explain -> {
//                        if (Objects.equals(explain.getAttr(), PayPlanEnum.STATUS.getAttr())) {
//                            for (ItemPoJo itemPoJo :explain.getItems()) {
//                              if (!canImportStatusList.contains(itemPoJo.getValue())) {
//                                  itemPoJo.setShowType(ShowTypeEnum.EXPORT_NO_IMPORT.getCode());
//                              }
//                            }
//                        }
//                    });
//                    break;
//                case CONTRACT:
//                    noImportAttr = Arrays.asList(PaymentEnum.REAL_AMOUNT.getAttr(), PaymentEnum.UN_AMOUNT.getAttr(), PaymentEnum.BAD_AMOUNT.getAttr(), PaymentEnum.INVOICE_AMOUNT.getAttr());
//                    explainList.removeIf(explain -> Objects.equals(formImportOrExport, ImportConstant.FROM_IMPORT) && noImportAttr.contains(explain.getAttr()));
//                    explainList.removeIf(explain-> Objects.equals(explain.getAttr(), PaymentEnum.BELONGER.getAttr())
//                            || Objects.equals(explain.getAttr(), PaymentEnum.PAYMENT_METHOD.getAttr()));
//                    List<String> canImportPaymentStatusList = Arrays.asList(PaymentStatusEnum.RECEIVABLES.getCode(), PaymentStatusEnum.UN_RECEIVABLES.getCode());
//                    explainList.forEach(explain -> {
//                        if (Objects.equals(explain.getAttr(), PaymentEnum.STATUS.getAttr())) {
//                            for (ItemPoJo itemPoJo :explain.getItems()) {
//                                if (!canImportPaymentStatusList.contains(itemPoJo.getValue())) {
//                                    itemPoJo.setShowType(ShowTypeEnum.EXPORT_NO_IMPORT.getCode());
//                                }
//                            }
//                        }
//                    });
//                    break;
//                default:
//                    break;
//            }
            SubFormPoJo subFormPoJo = new SubFormPoJo();
            subFormPoJo.setItems(explainList);
            linkFormField.setSubForm(subFormPoJo);
            linkFormField.setFieldType(FieldTypeEnum.SUB_FORM.getType());
        }
    }

    @Override
    public void handleCommonNeedTransferFields(List<FieldAttrEntityForImport> fieldAttrList, FormDataListDTO formDataListDTO) throws XbbException {
        for (FieldAttrEntityForImport item : fieldAttrList) {
            FieldTypeEnum fieldType = FieldTypeEnum.getFieldTypeEnum(item.getFieldType()) == null ? FieldTypeEnum.TEXT : FieldTypeEnum.getFieldTypeEnum(item.getFieldType());
            if (Objects.isNull(fieldType)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            switch (fieldType) {
                case SWITCH:
                    List<ItemPoJo> itemes = new ArrayList<>();
                    for (OperateTypeEnum operateTypeEnum: OperateTypeEnum.getSwitchByImport()) {
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setText(operateTypeEnum.getName());
                        itemPoJo.setValue(Integer.parseInt(operateTypeEnum.getAlias()));
                        itemes.add(itemPoJo);
                    }
                    item.setItems(itemes);
                    item.setFieldType(FieldTypeEnum.COMBO.getType());
                    break;
                case BIRTHDAY:
                    setBirthdayToSubForm(item);
                    break;
                case ADDRESS:
                    List<ImportEnum> fieldList;
                    Integer showDetailAddress = item.getShowDetailAddress();
                    if (Objects.equals(showDetailAddress, 1)) {
                        fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA, ImportEnum.DETAIL_ADDRESS);
                    } else {
                        fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA);
                    }
                    setSpecialRequiredFields2SubForm(item, fieldList);
                    break;
                case LOCATION:
                    fieldList = Arrays.asList(ImportEnum.PROVINCE, ImportEnum.CITY, ImportEnum.AREA, ImportEnum.DETAIL_ADDRESS);
                    setSpecialFields2SubForm(item, fieldList);
                    break;
                case HREF:
                    fieldList = Arrays.asList(ImportEnum.HREF_TEXT, ImportEnum.HREF_LINK);
                    setSpecialFields2SubForm(item, fieldList);
                    break;
                case CONTACT_NUMBER:
                    item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
                    item.setNeedImportSeparately(ImportConstant.NEED_IMPORT_SEPARATELY);
                    break;
                case STAR:
                    List<ItemPoJo> items = new ArrayList<>();
                    for(StarEnum starEnum : StarEnum.getStarsByImport()) {
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setText(starEnum.getText());
                        itemPoJo.setValue(starEnum.getValue());
                        items.add(itemPoJo);
                    }
                    item.setItems(items);
                    break;
                case SUB_FORM:
                    List<FieldAttrEntityForImport> fieldAttrEntityForImportList = JSON.parseArray(JSON.toJSONString(item.getSubForm().getItems()), FieldAttrEntityForImport.class);
                    if (Objects.nonNull(formDataListDTO) && Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(item.getAttr(), CustomerManagementEnum.ADD_CONTACT.getAttr()) && Objects.isNull(formDataListDTO.getIsContact())){
                        formDataListDTO.setIsContact(BasicConstant.ONE);
                        handleCommonNeedTransferFields(fieldAttrEntityForImportList, formDataListDTO);
                        formDataListDTO.setIsContact(null);
                    } else {
                        handleCommonNeedTransferFields(fieldAttrEntityForImportList, formDataListDTO);
                    }
                    SubFormPoJo subFormPoJo = new SubFormPoJo();
                    subFormPoJo.setItems(fieldAttrEntityForImportList);
                    item.setSubForm(subFormPoJo);
                    item.setNeedImportSeparately(ImportConstant.NEED_IMPORT_SEPARATELY);
                    break;
                case SINGLE_SUB_FORM:
                    item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
                    fieldAttrEntityForImportList = JSON.parseArray(JSON.toJSONString(item.getSubForm().getItems()), FieldAttrEntityForImport.class);;
                    handleCommonNeedTransferFields(fieldAttrEntityForImportList, formDataListDTO);
                    subFormPoJo = new SubFormPoJo();
                    subFormPoJo.setItems(fieldAttrEntityForImportList);
                    item.setSubForm(subFormPoJo);
                    break;
                case LINK_BUSINESS_SINGLE:
                    if (Objects.equals(item.getLinkedType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                        setLinkCustomerToSubForm(item);
                    }
                    break;
                case LABEL:
                    handleLabelFields(fieldAttrList, formDataListDTO);
                    break;
                case STAGE_THRUSTER:
                    item.setItems(proFormHelp.getEnableStageComboItems(formDataListDTO.getSaasMark(), formDataListDTO.getBusinessType()
                            , formDataListDTO.getCorpid(), formDataListDTO.getFormId()));
                    break;
                case TEMPLATE_FIELD:
                    fieldList = Arrays.asList(ImportEnum.TEMPLATE_NAME, ImportEnum.FILE);
                    setSpecialFields2SubForm(item, fieldList);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * saas导入保存
     *  @param importFormDataDTO 导入前端参数
     * @param totalRowNum 总行数
     * @param rowGroupPojoList 各行数据
     * @param titlePojoList 标题
     * @param fieldAttrEntityForImportList  需要批量查询的数据
     * @param checkRepeatKey
     */
    @Override
    public void importSaasData(ImportOtherParamsDTO importOtherParamsDTO, ImportFormDataDTO importFormDataDTO, int totalRowNum, List<RowGroupPojo> rowGroupPojoList, List<CellTitlePojo> titlePojoList, List<FieldAttrEntityForImport> fieldAttrEntityForImportList, String checkRepeatKey) throws Exception {
        long startTime = DateTimeUtil.getInt();
        String userId = importFormDataDTO.getUserId();
        // 缓存键
        String hashKey = importFormDataDTO.getCorpid() + "_" + importFormDataDTO.getUserId();
        Long formId = importFormDataDTO.getFormId();
        String formHashKey = hashKey + "_" + formId;
        // 导入状态   单条消息内 信息都是同一个用户的
        ImportStatusPojo importStatusPojo = new ImportStatusPojo();
        // 将表单信息等参数复制到pojo
        BeanUtil.copyProperties(importFormDataDTO,importStatusPojo);
        //
        Integer totalSize = importOtherParamsDTO.getTotalSize();
        importStatusPojo.setTotalNum(totalSize);
        // 存放excel中错误数据
        List<ErrorExcelDataPojo> errorList = new ArrayList<>();
        // 存放excel中重复数据
        List<ErrorExcelDataPojo> updateList = new ArrayList<>();
        // 存放excel中签订人错误数据
        List<ErrorExcelDataPojo> noSignPersonList = new ArrayList<>();
        // 存放重复数据，用于覆盖导入
        List<RowGroupPojo> repeatRowGroupPojoList = new ArrayList<>();
        // 存放需要放入自动分配的线索id
        List<Long> clueIds = new ArrayList<>();
        // 需要
        List<Long> bindGroupDataIds = new ArrayList<>();
        int nowRowNum = 0;
        int nowGroupNum = 0;
        // 导入查重,找出需查重字段
        List<String> noRepeatAttrNameList = new ArrayList<>();
        Map<String,String> noRepeatAttrNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Integer businessType = importFormDataDTO.getBusinessType();
        String corpid = importFormDataDTO.getCorpid();

        boolean publicPoolSeniorModel = false;
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            publicPoolSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);
        } else {
            publicPoolSeniorModel = commonHelp.isCluePublicPoolSeniorModel(corpid);
        }
        // 其他子表单不查重
        boolean needPhoneRepeatBusinessType = Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER_CONTACT.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode());

        boolean needSubFormRepeatBusinessType = Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode())
                || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode());

        List<String> attrList = new ArrayList<>();
        boolean hasSubFormCheckRepeat = false;
        String labelAttr = null;
        // 客户联系人的解释，用户客户联系人联合导入
        List<? extends FieldAttrEntity> contactFieldAttrEntityList = new ArrayList<>();
        //拿查重的字段
        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
            //首先上面有五个业务
            attrList.add(fieldAttrEntityForImport.getAttr());
            if (needPhoneRepeatBusinessType && Objects.equals(fieldAttrEntityForImport.getAttr(), StringConstant.PHONE_ATTR)) {
                List<FieldAttrEntityForImport> subFieldList = JSON.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems(), SerializerFeature.DisableCircularReferenceDetect), FieldAttrEntityForImport.class);
                for (FieldAttrEntityForImport field : subFieldList) {
                    if (Objects.equals(field.getNoRepeat(), 1)) {
                        String attrName = fieldAttrEntityForImport.getAttrName() + StringConstant.COMMA + field.getAttrName();
                        noRepeatAttrNameList.add(attrName);
                        noRepeatAttrNameMap.put(attrName,fieldAttrEntityForImport.getAttr() + StringConstant.COMMA + field.getAttr());
                        hasSubFormCheckRepeat = true;
                    }
                }
            } else if (needSubFormRepeatBusinessType && FieldTypeEnum.isSubFormType(fieldAttrEntityForImport.getFieldType()) && Objects.equals(fieldAttrEntityForImport.getIsRedundant(), BasicConstant.ONE) && !Objects.equals(fieldAttrEntityForImport.getAttr(), StringConstant.PHONE_ATTR)) {
                List<FieldAttrEntityForImport> subFieldList = JSON.parseArray(JSON.toJSONString(fieldAttrEntityForImport.getSubForm().getItems(), SerializerFeature.DisableCircularReferenceDetect), FieldAttrEntityForImport.class);
                for (FieldAttrEntityForImport field : subFieldList) {
                    if (Objects.equals(field.getNoRepeat(), 1)) {
                        String attrName = fieldAttrEntityForImport.getAttrName() + StringConstant.COMMA + field.getAttrName();
                        noRepeatAttrNameList.add(attrName);
                        noRepeatAttrNameMap.put(attrName,fieldAttrEntityForImport.getAttr() + StringConstant.COMMA + field.getAttr());
                        hasSubFormCheckRepeat = true;
                    }
                }
            } else {
                Integer noRepeat = fieldAttrEntityForImport.getNoRepeat();
                if (Objects.equals(noRepeat,1)) {
                    String attrName = fieldAttrEntityForImport.getAttrName();
                    noRepeatAttrNameList.add(attrName);
                    noRepeatAttrNameMap.put(attrName,fieldAttrEntityForImport.getAttr());
                }
                // 产品编号没有查重属性
                if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    if (Objects.equals(fieldAttrEntityForImport.getAttr(), ProductEnum.SERIALNO.getAttr()) || Objects.equals(fieldAttrEntityForImport.getAttr(), ProductEnum.BARCODE.getAttr())) {
                        String attrName = fieldAttrEntityForImport.getAttrName();
                        noRepeatAttrNameList.add(attrName);
                        noRepeatAttrNameMap.put(attrName,fieldAttrEntityForImport.getAttr());
                    }
                }
                //盘点单同一仓库只允许存在一个盘点单
                if(Objects.equals(XbbRefTypeEnum.INVENTORY.getCode(), businessType)){
                    if (Objects.equals(fieldAttrEntityForImport.getAttr(),InventoryEnum.WAREHOUSE_ID.getAttr())){
                        String attrName = fieldAttrEntityForImport.getAttrName();
                        noRepeatAttrNameList.add(attrName);
                        noRepeatAttrNameMap.put(attrName, fieldAttrEntityForImport.getAttr());
                    }
                }
                // 经销商账号管理手机号判重需要结合账号状态
                if (Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode())) {
                    // 账号管理es么有appId,这里移除掉
                    importFormDataDTO.setAppId(null);
                    if (Objects.equals(fieldAttrEntityForImport.getAttr(), DistributorAccountEnum.PHONE.getAttr())) {
                        String attrName = fieldAttrEntityForImport.getAttrName();
                        noRepeatAttrNameList.add(attrName);
                        noRepeatAttrNameMap.put(attrName,fieldAttrEntityForImport.getAttr());
                    }
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                        && Objects.equals(importFormDataDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())
                        && Objects.equals(fieldAttrEntityForImport.getAttr(), DistributorEnum.OWNER_ID.getAttr())) {
                    // 经销商导入的时候如果负责人不存在，会填充任意一个超管，这里先把必填去掉，后面会把值填上
                    fieldAttrEntityForImport.setRequired(0);
                }
            }
            if (Objects.equals(fieldAttrEntityForImport.getFieldType(), FieldTypeEnum.LABEL.getType())){
                labelAttr = fieldAttrEntityForImport.getAttr();
            }

            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                if (Objects.equals(fieldAttrEntityForImport.getAttr(), CustomerManagementEnum.ADD_CONTACT.getAttr())) {
                    contactFieldAttrEntityList = fieldAttrEntityForImport.getSubForm().getItems();
                }
            }
        }

        // 标签处理
        Map<String, JSONObject> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (StringUtil.isNotEmpty(labelAttr)){
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("formId", formId);
            param.put("enable", 0);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("columns", " id, lable_name ");
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            entitys.forEach(item->{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", item.getId());
                jsonObject.put("name", item.getName());
                labelPojoMap.put(item.getName(), jsonObject);
            });
        }

        // 联系人标签字段
        String contactLabelAttr = null;
        for (FieldAttrEntity fieldAttrEntity : contactFieldAttrEntityList) {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                contactLabelAttr = fieldAttrEntity.getAttr();
                break;
            }
        }
        Map<String, JSONObject> contactLabelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (StringUtil.isNotEmpty(contactLabelAttr)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.BUSINESS_TYPE, XbbRefTypeEnum.CONTACT.getCode());
            param.put("enable", 0);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("columns", " id, lable_name ");
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            entitys.forEach(item->{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", item.getId());
                jsonObject.put("name", item.getName());
                contactLabelPojoMap.put(item.getName(), jsonObject);
            });
        }

        List<Long> coverDataIdIn = new ArrayList<>();
        //需要覆盖的数据，（二次进入）
        rowGroupPojoList.forEach(rowGroupPojo -> {
            if (Objects.nonNull(rowGroupPojo.getDataId())) {
                coverDataIdIn.add(rowGroupPojo.getDataId());
            }
        });

        boolean needQueryCoverData = !coverDataIdIn.isEmpty() &&
                ((Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) && attrList.contains(ContractEnum.PRODUCT.getAttr()))
                        || (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode()) && (attrList.contains(PurchaseEnum.ADD_PAYPLAN.getAttr()) || attrList.contains(PurchaseEnum.PRODUCT.getAttr())))
                || (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && attrList.contains(CustomerManagementEnum.ADD_CONTACT.getAttr()))
                || Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode()));
        CoverExcelDataPojo coverExcelDataPojo = null;
        if (needQueryCoverData) {
            // 覆盖导入，获取数据
            // 客户和联系人一起导入时，获取客户下关联的联系人，用于后面删除联系人再次导入Excel中的联系人
            coverExcelDataPojo = queryCoverData4Import(businessType, corpid, coverDataIdIn);
        }
        //获取团队信息
        Map<Long, List<UserTeamEntity>> userTeamListMap = null;
        List<String> subIdList = null;
        if(CollectionsUtil.isNotEmpty(coverDataIdIn) && !Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
            //fix: 27606 【自定义表单-导出】自定义权限角色进行导入覆盖，应支持覆盖自身负责的单据
            if (UserTeamEnum.hasTeam(businessType)) {
                userTeamListMap = userTeamService.getMainUserTeamListMap(coverDataIdIn, importFormDataDTO.getCorpid(), importFormDataDTO.getBusinessType(), false);
            } else {
                userTeamListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(), coverDataIdIn));
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, importFormDataDTO.getSaasMark());
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType()));
                SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                searchSourceBuilder.query(boolQueryBuilder);
                SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
                searchRequest.source(searchSourceBuilder);
                PageRequest pageRequest = EsUtil.setPage(searchSourceBuilder, 1, ExcelConstant.PER_READ_INSERT_BATCH_COUNT);
                List<PaasFormDataEntity> paasFormDataEntityList = xbbElasticsearchRestTemplate.queryForList(pageRequest, searchRequest, PaasFormDataEntity.class);
                for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntityList) {
                    userTeamListMap.put(paasFormDataEntity.getDataId(), Collections.singletonList(new UserTeamEntity(corpid, paasFormDataEntity.getOwnerId())));
                }
            }
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(importFormDataDTO.getLoginUser(), userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, false);
            subIdList = userModel.getSubIdListByDataPermission(dataPermission, userId, corpid, BasicConstant.ZERO, true );
        }
        // userMap
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put(ParameterConstant.CORPID, corpid);
            params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            List<UserEntity> userEntityList = userModel.findEntitys(params);
            for (UserEntity userEntity : userEntityList) {
                userMap.put(userEntity.getUserId(), userEntity);
            }
        }

        // 查重字段-值map
        Map<String,List<Object>> repeatValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,List<Object>> subRepeatValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<String> uniqueIdentityNameList = new HashSet<>();
        for (RowGroupPojo rowGroupPojo : rowGroupPojoList) {
            uniqueIdentityNameList.add(rowGroupPojo.getGroupTagValue());

            nowRowNum += rowGroupPojo.getRowValueList().size();
            nowGroupNum ++;
            // 每隔10组数据导完时，刷新一次当前导入状态
            if (nowGroupNum % 10 == 0 || nowRowNum >= totalRowNum) {
                importRedisHelper.updateImportStatus(hashKey, importStatusPojo, 0);
                paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey, BasicConstant.ONE_STRING, TimeConstant.SECONDS_EIGHT_HOUR);
                //防置完成之后清空，因为上面做的是+=
                importStatusPojo.setSuccessNum(0);
                importStatusPojo.setErrorNum(0);
                importStatusPojo.setUpdateNum(0);
                importStatusPojo.setNoSignNum(0);
            }
            try {
                List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
                // 分组的第一条数据作为给实体对象赋值的数据
                List<CellValuePojo> cellValueList = rowValueList.get(0);
                // 校验必填字段是否为空
                importHelper.checkImportData(cellValueList, titlePojoList, fieldAttrEntityForImportList, null);
                // 校验数字小数精度
                importHelper.checkImportDataForNum(cellValueList, titlePojoList, fieldAttrEntityForImportList, null, corpid, importFormDataDTO.getUserId(), businessType);
                // excel内数据不可重复(excel自身的判重)
                for (CellValuePojo cellValuePojo : cellValueList) {
                    String parentTitle = cellValuePojo.getParentTitle();
                    String title = cellValuePojo.getTitle();
                    if (Objects.nonNull(parentTitle)) {
                        title = parentTitle + StringConstant.COMMA + title;
                    }
                    if (noRepeatAttrNameList.contains(title)) {
                        List<Object> valueList = new ArrayList<>();
                        if (repeatValueMap.containsKey(title)) {
                            valueList = repeatValueMap.get(title);
                        }
                        Object value = cellValuePojo.getValue();
                        if (Objects.nonNull(value) && StringUtil.isNotEmpty(value.toString())) {
                            if (valueList.contains(value)) {
                                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235017, String.format(ImportErrorCodeEnum.API_ERROR_235017.getMsg(), title));
                            }
                            valueList.add(value);
                            repeatValueMap.put(title, valueList);
                        }
                    }
                }
                if (hasSubFormCheckRepeat) {
                    for (List<CellValuePojo> cellValuePojoList : rowValueList) {
                        for (CellValuePojo cellValuePojo : cellValuePojoList) {
                            String parentTitle = cellValuePojo.getParentTitle();
                            String title = cellValuePojo.getTitle();
                            if (Objects.nonNull(parentTitle)) {
                                title = parentTitle + StringConstant.COMMA + title;
                                if (noRepeatAttrNameList.contains(title)) {
                                    List<Object> valueList = new ArrayList<>();
                                    if (subRepeatValueMap.containsKey(title)) {
                                        valueList = subRepeatValueMap.get(title);
                                    }
                                    Object value = cellValuePojo.getValue();
                                    if (Objects.nonNull(value) && StringUtil.isNotEmpty(value.toString())) {
                                        if (valueList.contains(value)) {
                                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235017, String.format(ImportErrorCodeEnum.API_ERROR_235017.getMsg(), title));
                                        }
                                        valueList.add(value);
                                        subRepeatValueMap.put(title, valueList);
                                    }
                                }
                            }
                        }
                    }
                }
                FormDataAddDTO formDataAddDTO = formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrEntityForImportList, contactLabelAttr, contactLabelPojoMap);
                // 标签处理
                if (StringUtil.isNotEmpty(labelAttr)){
                    if (Objects.nonNull(formDataAddDTO.getDataList().get(labelAttr))){
                        String[] split = formDataAddDTO.getDataList().getString(labelAttr).split(",");
                        Set<String> labelIdName = new HashSet(Arrays.asList(split));
                        JSONArray jsonArray1 = new JSONArray();
                        for (String aLong : labelIdName) {
                            if (Objects.nonNull(labelPojoMap.get(aLong))) {
                                jsonArray1.add(labelPojoMap.get(aLong));
                            }
                        }
                        formDataAddDTO.getDataList().put(labelAttr, jsonArray1);
                    }
                }
                if (Objects.nonNull(formDataAddDTO.getDataList()) && Objects.nonNull(formDataAddDTO.getDataList().get(FieldTypeEnum.OWNERID.getAlias()))) {
                    List<ReturnUserAndDepartmentPojo> ownerIds = formDataAddDTO.getDataList().getJSONArray(FieldTypeEnum.OWNERID.getAlias()).toJavaList(ReturnUserAndDepartmentPojo.class);
                    List<ReturnUserAndDepartmentPojo> distinctList = ownerIds.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(entry -> entry.getId().toString()))), ArrayList::new));
                    formDataAddDTO.setOwnerId(distinctList);
                    formDataAddDTO.getDataList().remove(FieldTypeEnum.OWNERID.getAlias());
                }
                formDataAddDTO.setIsImport(1);
                Object versionValue = new Object();
                Object groupNumberValue = new Object();
                Object nameValue = new Object();
                Map<String,Object> repeatQuotationValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                //报价单历史版本导入强校验（不让导入）
                if (Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode())) {
                    String name = "";
                    //拿字段名(管理中心可修改字段名)
                    for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
                        if (Objects.equals(fieldAttrEntityForImport.getAttr(), QuotationEnum.NAME.getAttr())) {
                            name = fieldAttrEntityForImport.getAttrName();
                        }
                    }
                    for (CellValuePojo cellValuePojo : cellValueList) {
                        if (Objects.equals(cellValuePojo.getTitle(), QuotationEnum.VERSION.getAttrName() + "*")) {
                            versionValue = cellValuePojo.getValue();
                        } else if (Objects.equals(cellValuePojo.getTitle(), QuotationEnum.GROUP_NUMBER.getAttrName() + "*")) {
                            groupNumberValue = cellValuePojo.getValue();
                        } else if (Objects.equals(cellValuePojo.getTitle(), name + StringConstant.SPECIALMODEL) || Objects.equals(cellValuePojo.getTitle(), name)) {
                            nameValue = cellValuePojo.getValue();
                        }
                    }
                    if (!checkQuotation(importFormDataDTO, groupNumberValue, versionValue, importStatusPojo, errorList, updateList, noSignPersonList, rowGroupPojo)) {
                        continue;
                    }
                    //新主题报价单以报价单编号为唯一标示（报价名称防重复开启是提示名称重复）
                    if (!checkNewQuotationName(importFormDataDTO, groupNumberValue, versionValue, noRepeatAttrNameList, noRepeatAttrNameMap, importStatusPojo, errorList, updateList, noSignPersonList, rowGroupPojo, nameValue, fieldAttrEntityForImportList)) {
                        continue;
                    }
                }
                Integer isCover = importFormDataDTO.getIsCover();
                if (Objects.equals(1,isCover)) {
                    // 覆盖
                    FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
                    if (Objects.nonNull(coverExcelDataPojo)) {
                        coverExcelDataPojo.setFormDataAddDTO(formDataAddDTO);
                        coverExcelDataPojo.setDataId(rowGroupPojo.getDataId());
                        coverExcelDataPojo.setFieldAttrEntityForImportList(fieldAttrEntityForImportList);
                        formDataAddDTO = formatCoverExcelValue(coverExcelDataPojo, coverDataIdIn);
                    }
//                    if (!Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
//                        boolean hasPermission = saasDetailPermissionHelp.checkPermissionOption(importFormDataDTO.getLoginUser(),userTeamListMap.get(rowGroupPojo.getDataId()),subIdList);
//                        if(!hasPermission){
//                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235014);
//                        }
//                    }
                    BeanUtil.copyProperties(formDataAddDTO,formDataUpdateDTO);
                    formDataUpdateDTO.setDataId(rowGroupPojo.getDataId());
                    formDataUpdateDTO.setIsCover(isCover);
                    if (Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                        priceSetService.importCover(formDataUpdateDTO);
                    } else if (XbbRefTypeEnum.workOrderV2Form().contains(businessType)) {
                        workOrderV2ImportHelp.updateAndImport(formDataUpdateDTO);
                    } else {
                        FormDataUpdateVO update = paasFormDataService.update(formDataUpdateDTO);
                        Long backupDataId = update.getBackupDataId();
                    }
                } else {
                    //报价单新版本跳过报价单名称防重复校验（version > 1.0即为新版本）
                    if (Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode())) {
                        String serialNoName = QuotationEnum.NAME.getAttrName();
                        String quotationName = "";
                        //拿字段名(管理中心可修改字段名)
                        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {

                            if (Objects.equals(fieldAttrEntityForImport.getAttr(), QuotationEnum.NAME.getAttr())) {
                                quotationName = fieldAttrEntityForImport.getAttrName();
                            }
                        }
                        for (CellValuePojo cellValuePojo : cellValueList) {
                            if (Objects.equals(cellValuePojo.getTitle(), QuotationEnum.VERSION.getAttrName() + "*")) {
                                Object value = cellValuePojo.getValue();
                                String values = value.toString();
                                if (!values.matches(RegExConstant.QUOTATION_VERSION)) {
                                    if (values.matches(RegExConstant.QUOTATION_INTFER)) {
                                        StringBuilder stringBuilder = new StringBuilder();
                                        stringBuilder.append(values);
                                        stringBuilder.append(".0");
                                        values = stringBuilder.toString();
                                    }
                                }
                                if (!Objects.equals(values, StringConstant.DEFAULT_VERSION)) {
                                    // 隐藏逻辑，当版本号非1.0时，则表示为新版本，将移掉报价单名称的查重逻辑，坑死我了，查了半天 by @date 2021/3/29 11:33 吴峰 add/update改造需求
                                    String finalQuotationName = quotationName;
                                    noRepeatAttrNameList = noRepeatAttrNameList.stream().filter(p -> !Objects.equals(finalQuotationName, p)).collect(Collectors.toList());
                                    noRepeatAttrNameMap.entrySet().removeIf(entry -> Objects.equals(entry.getKey(), finalQuotationName));
                                }
                            } else if (Objects.equals(cellValuePojo.getTitle(), QuotationEnum.GROUP_NUMBER.getAttrName() + "*")) {
                                formDataAddDTO.setGroupNumber(Objects.toString(cellValuePojo.getValue(), ""));
                            }
                        }
                        //手动添加报价单编号防重复校验
                        String groupNumber = groupNumberValue.toString();
                        String version = versionValue.toString();
                        if (!version.matches(RegExConstant.QUOTATION_VERSION)) {
                            if (version.matches(RegExConstant.QUOTATION_INTFER)) {
                                StringBuilder stringBuilder = new StringBuilder();
                                stringBuilder.append(version);
                                stringBuilder.append(".0");
                                version = stringBuilder.toString();
                            }
                        }
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append(groupNumber);
                        stringBuilder.append(version);
                        String serialNo = stringBuilder.toString();

                        repeatQuotationValueMap.put(QuotationEnum.QUOTATION_NO.getAttr(), serialNo);
                        noRepeatAttrNameList.add(serialNoName);
                        noRepeatAttrNameMap.put(serialNoName, serialNo);
                    }
                    if (!checkRepeat(importFormDataDTO, importStatusPojo, errorList, updateList, noSignPersonList, repeatRowGroupPojoList, noRepeatAttrNameList, noRepeatAttrNameMap, rowGroupPojo, repeatQuotationValueMap, formDataAddDTO.getExplainMap(), formDataAddDTO.getDataList())) {
                        continue;
                    }
                    Long dataId = null;
                    if (Objects.equals(formDataAddDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && !Objects.equals(formDataAddDTO.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_FOCUS.getCode())) {
                        formDataAddDTO.setExplainMap(importFormDataDTO.getExplainMap());
                        ExcelImportExtraPoJo excelImportExtraPoJo = new ExcelImportExtraPoJo();
                        excelImportExtraPoJo.setUserMap(userMap);
                        FormDataAddVO addVO = excelImportService.addImportData(formDataAddDTO, excelImportExtraPoJo);
                        dataId = addVO.getDataId();
                        if (publicPoolSeniorModel && Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                            // 导入新建的线索需要给他们放到绑定公海分组的消息队列里
                            bindGroupDataIds.add(addVO.getDataId());
                        }
                    } else if (Objects.equals(formDataAddDTO.getBusinessType(), XbbRefTypeEnum.ORI_STOCK.getCode())) {
                        OriStockSaveDTO oriStockSaveDTO = new OriStockSaveDTO();
                        BeanUtil.copyProperties(formDataAddDTO, oriStockSaveDTO);
                        FormDataAddVO addVO = oriStockService.add(oriStockSaveDTO);
                        dataId = addVO.getDataId();
                    } else if (Objects.equals(formDataAddDTO.getBusinessType(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
                        knowledgeDataService.importKnowledges(formDataAddDTO);
                    } else if (Objects.equals(formDataAddDTO.getBusinessType(), XbbRefTypeEnum.SERVICE_PROJECT.getCode())) {
                        FormDataAddVO addVO = workOrderV2ImportHelp.addAndImport(formDataAddDTO);
                        dataId = addVO.getDataId();
                        // 后续操作
                    } else if (Objects.equals(formDataAddDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER_V2.getCode())){
                        FormDataAddVO addVO = workOrderV2ImportHelp.addAndImport(formDataAddDTO);
                        dataId = addVO.getDataId();
                    } else {
                        FormDataAddVO addVO = paasFormDataService.add(formDataAddDTO);
                        dataId = addVO.getDataId();
                        if (publicPoolSeniorModel && Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                            // 导入新建的线索需要给他们放到绑定公海分组的消息队列里
                            bindGroupDataIds.add(addVO.getFormDataId());
                        }
                        if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(formDataAddDTO.getDataList().getInteger(ClueEnum.IS_PUBLIC.getAttr()), 1)) {
                            // 导入新建的线索直接进入公海池的，需要给他们放到自动分配的消息队列里
                            clueIds.add(addVO.getFormDataId());
                        }
                    }
                    // 如果是带附件的导入，将附件保存进文件柜。
                    if (Objects.equals(1, formDataAddDTO.getIsImport()) && Objects.nonNull(dataId)) {
                        List<CabinetFileEntity> cabinetFileEntityAddList = new ArrayList<>();
                        JSONObject dataJSONObject = formDataAddDTO.getDataList();
                        Map<String, FieldAttrEntity> explainMap = formDataAddDTO.getExplainMap();
                        for (JSONObject.Entry<String, Object> entry : dataJSONObject.entrySet()) {
                            String attrKey = entry.getKey();
                            FieldAttrEntity fieldAttrEntity = explainMap.get(attrKey);
                            if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())
                                    && Objects.nonNull(entry.getValue()) && StringUtil.isNotEmpty(entry.getValue().toString())) {
                                List<CabinetFileEntity> cabinetFileEntityList = JSONArray.parseArray(entry.getValue().toString(), CabinetFileEntity.class);
                                if (CollectionsUtil.isNotEmpty(cabinetFileEntityList)) {
                                    Long finalDataId = dataId;
                                    cabinetFileEntityList.forEach(e -> {
                                        e.setCorpid(corpid);
                                        e.setUserId(userId);
                                        e.setBusinessType(businessType);
                                        e.setDataId(finalDataId);
                                        e.setAddTime(DateTimeUtil.getInt());
                                        e.setDel(DelEnum.NORMAL.getDel());
                                        // 2为文件导入
                                        e.setType(2);
                                    });
                                    if (CollectionsUtil.isNotEmpty(cabinetFileEntityList)) {
                                        cabinetFileEntityAddList.addAll(cabinetFileEntityList);
                                    }
                                }
                                // 如果为子表单，只插入子表单下面一个层级
                            } else if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.SUB_FORM.getType())
                                    && Objects.nonNull(entry.getValue()) && StringUtil.isNotEmpty(entry.getValue().toString())) {
                                SubFormPoJo subForm = fieldAttrEntity.getSubForm();
                                if (Objects.nonNull(subForm) && CollectionsUtil.isNotEmpty(subForm.getItems())) {
                                    List<String> fileAttrList = subForm.getItems().stream().filter(item -> Objects.equals(item.getFieldType(), FieldTypeEnum.UPLOAD.getType())).map(e -> e.getAttr()).collect(Collectors.toList());
                                    if (CollectionsUtil.isNotEmpty(fileAttrList)) {
                                        JSONArray value = (JSONArray) entry.getValue();
                                        for (int j = 0; j < value.size(); j++) {
                                            JSONObject jsonObject = value.getJSONObject(j);
                                            if (Objects.isNull(jsonObject)) {
                                                continue;
                                            }
                                            for (String attr : fileAttrList) {
                                                for (int i = 0; i < value.size(); i++) {
                                                    List<CabinetFileEntity> cabinetFileEntityList = JSONArray.parseArray(jsonObject.getString(attr), CabinetFileEntity.class);
                                                    if (CollectionsUtil.isNotEmpty(cabinetFileEntityList)) {
                                                        Long finalDataId = dataId;
                                                        cabinetFileEntityList.forEach(e -> {
                                                            e.setCorpid(corpid);
                                                            e.setUserId(userId);
                                                            e.setBusinessType(businessType);
                                                            e.setDataId(finalDataId);
                                                            e.setAddTime(DateTimeUtil.getInt());
                                                            e.setDel(DelEnum.NORMAL.getDel());
                                                            // 2为文件导入
                                                            e.setType(2);
                                                        });
                                                        if (CollectionsUtil.isNotEmpty(cabinetFileEntityList)) {
                                                            cabinetFileEntityAddList.addAll(cabinetFileEntityList);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (CollectionsUtil.isNotEmpty(cabinetFileEntityAddList)) {
                            cabinetFileModel.insertBatch(cabinetFileEntityAddList);
                        }
                    }
                }
                int successNum = importStatusPojo.getSuccessNum();
                successNum += rowGroupPojo.getRowValueList().size();
                importStatusPojo.setSuccessNum(successNum);
            } catch (Exception e) {
                LOG.warn("导入数据异常", e);
                // 放入错误excel,并增加错误数或重复数
                putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,e,importStatusPojo);
            }finally {
                paasRedisHelper.removeValue(RedisPrefixConstant.LINK_DATA_NUM, formHashKey + "_" + Thread.currentThread().getId());
                paasRedisHelper.removeValue(RedisPrefixConstant.LINK_DATA_MULTI_NUM, formHashKey + "_" + Thread.currentThread().getId());
            }
        }

        if (Objects.nonNull(uniqueIdentityNameList)) {
            uniqueIdentityNameList.removeAll(Collections.singleton(null));
            if (uniqueIdentityNameList.size() > 0) {
                importRedisHelper.removeCheckRepeatValue(checkRepeatKey, uniqueIdentityNameList);
            }
        }

        // 存redis缓存
        if (!errorList.isEmpty()) {
            // 错误excel数据存缓存
            importRedisHelper.updateImportList(RedisPrefixConstant.IMPORT_ERROR_EXCEL_KEY, formHashKey, errorList, RedisConstant.LONG_DURATION);
            errorList.clear();
            paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_TITLE_LIST_KEY,formHashKey,titlePojoList,RedisConstant.LONG_DURATION);
            paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_EXPLAIN,formHashKey,fieldAttrEntityForImportList,RedisConstant.LONG_DURATION);
        }
        if (!updateList.isEmpty()) {
            // 重复excel数据存缓存
            importRedisHelper.updateImportList(RedisPrefixConstant.IMPORT_UPDATE_EXCEL_KEY, formHashKey, updateList, RedisConstant.LONG_DURATION);
            updateList.clear();
        }
        if (!noSignPersonList.isEmpty()) {
            // 无签订人excel数据存缓存
            importRedisHelper.updateImportList(RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_KEY, formHashKey, noSignPersonList, RedisConstant.LONG_DURATION);
            noSignPersonList.clear();
            paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_TITLE_LIST_KEY,formHashKey,titlePojoList,RedisConstant.LONG_DURATION);
        }
        if (!repeatRowGroupPojoList.isEmpty()) {
            // 覆盖导入所需数据存缓存
            importRedisHelper.updateImportList(RedisPrefixConstant.IMPORT_REPEAT_DATA_LIST_KEY, formHashKey, repeatRowGroupPojoList, RedisConstant.LONG_DURATION);
            repeatRowGroupPojoList.clear();
            paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_TITLE_LIST_KEY,formHashKey,titlePojoList,RedisConstant.LONG_DURATION);
            paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_EXPLAIN,formHashKey,fieldAttrEntityForImportList,RedisConstant.LONG_DURATION);
        }
        if (!clueIds.isEmpty()) {
            AutoClueAssignmentRabbitMqDTO mqDTO = new AutoClueAssignmentRabbitMqDTO(corpid, clueIds, formId);
            autoClueAssignmentProducer.autoClueAssignment(mqDTO);
        }

        if (!bindGroupDataIds.isEmpty()) {
            PublicGroupRabbitMqDTO publicGroupRabbitMqDTO = new PublicGroupRabbitMqDTO(corpid, bindGroupDataIds, formId,importFormDataDTO.getBusinessType());
            publicGroupProducer.bindPublicGroup(publicGroupRabbitMqDTO);
        }

        ImportStatusPojo statusPojo = importRedisHelper.updateImportStatus(hashKey, importStatusPojo, 1);
        paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_START_FLAG_KEY, hashKey, BasicConstant.ONE_STRING, TimeConstant.SECONDS_EIGHT_HOUR);
        if (statusPojo.getFinish()) {
            // 记录日志(导入，覆盖是两个操作，分别记录数量)
            try {
                insertLog(importFormDataDTO, statusPojo, businessType, corpid);
            } catch (Exception e) {
                LOG.error("导入日志记录出错：", e);
            }

            // import总耗时日志
            try {
                String logTime = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_LOG_TIME, hashKey);
                String startImportTime = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_LOG_START_TIME, hashKey);
                long endTime = DateTimeUtil.getInt();
                Long totalTime = 0L;
                if (StringUtil.isNotEmpty(logTime)) {
                    totalTime = Long.valueOf(logTime);
                }
                totalTime += (endTime - startTime);
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                LOG.warn("import_" + corpid + "_" + userId + "_" + xbbRefTypeEnum.getAlias() + "_end,time=" + DateTimeUtil.getString(endTime * 1000) + ",spendTime=" + DateTimeUtil.secondToTime(totalTime) + ", totalSize=" + totalSize + ",usingTime=" + DateTimeUtil.secondToTime(endTime - (Long.valueOf(startImportTime) / 1000)));
            } catch (Exception e) {
                LOG.error("import总耗时日志记录出错：", e);
            }
            // 用完清除
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_LOG_TIME, hashKey);
            paasRedisHelper.removeValue(RedisPrefixConstant.IMPORT_LOG_START_TIME, hashKey);

            // 自动生成错误Excel
            if (Objects.nonNull(statusPojo.getErrorNum()) && statusPojo.getErrorNum() > 1000) {
                createErrorOrUpdateExcel(fieldAttrEntityForImportList, businessType, DownloadExcelTypeEnum.ERROR, titlePojoList, corpid, userId, formId, importFormDataDTO.getMenuId());
            }
            if (Objects.nonNull(statusPojo.getUpdateNum()) && statusPojo.getUpdateNum() > 1000) {
                createErrorOrUpdateExcel(fieldAttrEntityForImportList, businessType, DownloadExcelTypeEnum.UPDATE, titlePojoList, corpid, userId, formId, importFormDataDTO.getMenuId());
            }
            if (Objects.nonNull(statusPojo.getNoSignNum()) && statusPojo.getNoSignNum() > 1000) {
                createErrorOrUpdateExcel(fieldAttrEntityForImportList, businessType, DownloadExcelTypeEnum.NO_SIGN, titlePojoList, corpid, userId, formId, importFormDataDTO.getMenuId());
            }

        } else {
            try {
                long endTime = DateTimeUtil.getInt();
                //耗时统计计算
                String time = paasRedisHelper.getValue(RedisPrefixConstant.IMPORT_LOG_TIME, hashKey);
                long timeLong;
                if (Objects.isNull(time)) {
                    timeLong = 0L;
                } else {
                    timeLong = Long.valueOf(time);
                }
                timeLong = timeLong + (endTime - startTime);
                paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_LOG_TIME, hashKey, timeLong, RedisConstant.LONG_DURATION);
            } catch (Exception e) {
                LOG.error("import耗时增量日志记录出错：", e);
            }
        }

    }

    private void createErrorOrUpdateExcel(List<FieldAttrEntityForImport> fieldAttrEntityForImportList, Integer businessType, DownloadExcelTypeEnum downloadExcelTypeEnum, List<CellTitlePojo> titlePojoList, String corpid, String userId, Long formId, Long menuId) {
        Workbook workbook = null;
        try {

            PaasMenuEntity paasMenuEntity = null;

            if (Objects.equals(businessType, XbbRefTypeEnum.ORI_STOCK.getCode())) {
                paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setName(XbbRefTypeEnum.ORI_STOCK.getName());
            } else if (Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                paasMenuEntity = new PaasMenuEntity();
                paasMenuEntity.setName(XbbRefTypeEnum.PRICE_SET_PRODUCT.getName());
            } else {
                paasMenuEntity = paasMenuModel.getByKey(menuId, corpid);
            }
            if (paasMenuEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }

            JSONArray dataExplain = JSON.parseArray(JSON.toJSONString(fieldAttrEntityForImportList));
//            workbook = null;
            workbook = excelOperatorService.createExcelTemplate(businessType, dataExplain, paasMenuEntity.getName(), downloadExcelTypeEnum.getType(), 0, false);

            // 第一列错误信息处理
            if (Objects.equals(downloadExcelTypeEnum, DownloadExcelTypeEnum.ERROR)) {
                titlePojoList.forEach(v -> v.setColumnIndex(v.getColumnIndex() + 1));
                titlePojoList.add(0, new CellTitlePojo(DownloadExcelTypeEnum.ERROR.getMsg(), 0));
            }

            Map<String, Integer> titleIndexMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            titlePojoList.forEach(item -> {
                String parent = item.getParentTitle() == null ? "" : item.getParentTitle();
                String secondParent = item.getSecondParentTitle() == null ? "" : item.getSecondParentTitle();
                String thirdParent = item.getThirdParentTitle() == null ? "" : item.getThirdParentTitle();
                titleIndexMap.put(thirdParent + secondParent + parent + item.getTitle(), item.getColumnIndex());
            });

            String redisKey;
            // 是否是下载错误excel
            if (Objects.equals(DownloadExcelTypeEnum.UPDATE, downloadExcelTypeEnum)) {
                redisKey = RedisPrefixConstant.IMPORT_UPDATE_EXCEL_KEY;
            } else if (Objects.equals(DownloadExcelTypeEnum.ERROR, downloadExcelTypeEnum)) {
                redisKey = RedisPrefixConstant.IMPORT_ERROR_EXCEL_KEY;
            } else if (Objects.equals(DownloadExcelTypeEnum.NO_SIGN, downloadExcelTypeEnum)) {
                redisKey = RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_KEY;
            } else {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002);
            }

            String hashKey = corpid + "_" + userId;
            String formHashKey = hashKey + "_" + formId;

            Long start = 0L;
            Integer pageSize = ExcelConstant.PER_READ_INSERT_BATCH_COUNT;
            while (true) {
                Long end = start + pageSize;

                List<String> importList = importRedisHelper.getImportList(redisKey, formHashKey, start, end);

                if (CollectionsUtil.isEmpty(importList)) {
                    break;
                }
                start = end + 1;

                for (String obj : importList) {
                    // 遍历数据，插入workbook
                    JSONObject errorObj = JSONObject.parseObject(obj);
                    String msg = errorObj.getString("msg");
                    String listStr = errorObj.getString("rowGroupPojo");
                    JSONObject rowGroupPojo = JsonHelperUtil.parseObject(listStr);
                    String rowValueListStr = rowGroupPojo.getString("rowValueList");
                    JSONArray rowValueArray = JsonHelperUtil.parseArray(rowValueListStr);
                    List<List<CellValuePojo>> rowValueList = new ArrayList<>();
                    for (int i = 0; i < rowValueArray.size(); i++) {
                        JSONArray jsonArray = rowValueArray.getJSONArray(i);
                        List<CellValuePojo> cellValuePojoList = JsonHelperUtil.parseArray(jsonArray.toJSONString(), CellValuePojo.class);
                        rowValueList.add(cellValuePojoList);
                    }

                    boolean isErrorExcel = false;
                    if (Objects.equals(downloadExcelTypeEnum, DownloadExcelTypeEnum.ERROR)) {
                        CellValuePojo cellValuePojoFirst;
                        for (List<CellValuePojo> valuePojos : rowValueList) {
                            isErrorExcel = true;
                            cellValuePojoFirst = valuePojos.get(0);
                            if (DownloadExcelTypeEnum.ERROR.getMsg().equals(cellValuePojoFirst.getTitle())) {
                                // 已经有错误信息列,不再index后移,并且之前的错误列移除
                                isErrorExcel = false;
                                valuePojos.remove(0);
                            }
                            // 插入错误列
                            CellValuePojo cellValuePojo = new CellValuePojo(msg, DownloadExcelTypeEnum.ERROR.getMsg(),null,0);
                            valuePojos.add(0,cellValuePojo);
                        }
                    }
                    ExcelUtil.addExcelContent(workbook, rowValueList, isErrorExcel, titleIndexMap, fieldAttrEntityForImportList, businessType);
                }
            }

            // 上传到oss
            String name = "";
            if (Objects.equals(DownloadExcelTypeEnum.UPDATE, downloadExcelTypeEnum)) {
                name = I18nMessageUtil.getMessage(I18nStringConstant.REPEAT_DATA_EXCEL);
            } else if (Objects.equals(DownloadExcelTypeEnum.ERROR, downloadExcelTypeEnum)) {
                name = I18nMessageUtil.getMessage(I18nStringConstant.ERROR_DATA_EXCEL);
            } else if (Objects.equals(DownloadExcelTypeEnum.NO_SIGN, downloadExcelTypeEnum)) {
                name = I18nMessageUtil.getMessage(I18nStringConstant.SIGN_ERROR_DATA_EXCEL);
            }


            name = corpid + "/" + userId + "/xlsx/" + name;
            String url = ossHelper.putObjectWorkbook(workbook, name);

            if (Objects.equals(DownloadExcelTypeEnum.UPDATE, downloadExcelTypeEnum)) {
                paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_UPDATE_EXCEL_OSS_KEY, hashKey, url, RedisConstant.LONG_DURATION);
            } else if (Objects.equals(DownloadExcelTypeEnum.ERROR, downloadExcelTypeEnum)) {
                paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_ERROR_EXCEL_OSS_KEY, hashKey, url, RedisConstant.LONG_DURATION);
            } else if (Objects.equals(DownloadExcelTypeEnum.NO_SIGN, downloadExcelTypeEnum)) {
                paasRedisHelper.setValue(RedisPrefixConstant.IMPORT_NO_SIGN_EXCEL_OSS_KEY, hashKey, url, RedisConstant.LONG_DURATION);
            }


        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.impl.HandleImportServiceImpl.createErrorOrUpdateExcel fail", e);
        } finally {
            if (Objects.nonNull(workbook)) {
                try {
                    workbook.close();
                } catch (IOException e1) {
                    LOG.error("关闭workbook错误", e1);
                }catch (Exception e1) {
                    LOG.error("关闭workbook错误", e1);
                }
            }
        }
    }

    private void insertLog(ImportFormDataDTO importFormDataDTO, ImportStatusPojo importStatusPojo, Integer businessType, String corpid) {
        Integer isCover = importFormDataDTO.getIsCover();
        String userName = importFormDataDTO.getLoginUserName();
        String userId = importFormDataDTO.getUserId();
        Integer successNum = importStatusPojo.getSuccessNum();
        Integer errorNum = importStatusPojo.getErrorNum();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(businessType,importFormDataDTO.getDistributorMark()));
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(importFormDataDTO.getFormId(), corpid);
        String paasFormName = "";
        if ( Objects.nonNull(paasFormEntityExt) ) {
            paasFormName = paasFormEntityExt.getName();
        }
        if ( Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode()) ) {
            paasFormName = XbbRefTypeEnum.PRICE_SET_PRODUCT.getName();
        }
        String memo = null;
        OperateModuleTypeEnum operateModuleTypeEnum = null;
        if (Objects.equals(1, isCover)) {
            // 覆盖日志
            if (SaasMarkEnum.PAAS.getCode().equals(importFormDataDTO.getSaasMark())) {
                if (paasFormEntityExt != null) {
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_COVERAGE), userName, paasFormName, successNum, errorNum);
                    operateModuleTypeEnum = OperateModuleTypeEnum.PAAS_FORM_DATA;
                }
            } else {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_COVERAGE), userName, paasFormName, successNum, errorNum);
                operateModuleTypeEnum = logHelp.getOperateModuleTypeEnum(xbbRefTypeEnum);
            }
            try {
                mongoLogHelp.buildLog(corpid, userId, userName, operateModuleTypeEnum, OperateTypeEnum.COVERAGE, "",
                        "", memo, importFormDataDTO.getHttpHeader());
            } catch (XbbException e) {
                LOG.error("导入覆盖日志记录出错：", e);
            }
        } else {
            // 导入日志
            if (SaasMarkEnum.PAAS.getCode().equals(importFormDataDTO.getSaasMark())) {
                if (paasFormEntityExt != null) {
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_IMPORT), userName, paasFormName, successNum, errorNum);
                    operateModuleTypeEnum = OperateModuleTypeEnum.PAAS_FORM_DATA;
                }
            } else {
                if (paasFormEntityExt != null) {
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_IMPORT), userName, paasFormName, successNum, errorNum);
                    operateModuleTypeEnum = logHelp.getOperateModuleTypeEnum(xbbRefTypeEnum);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.ORI_STOCK.getCode())) {
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_IMPORT), userName, OperateModuleTypeEnum.ORI_STOCK.getName(), successNum, errorNum);
                    operateModuleTypeEnum = logHelp.getOperateModuleTypeEnum(xbbRefTypeEnum);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_IMPORT), userName, OperateModuleTypeEnum.PRICE_SET.getName(), successNum, errorNum);
                    operateModuleTypeEnum = logHelp.getOperateModuleTypeEnum(xbbRefTypeEnum);
                }else if (Objects.equals(businessType, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
                    KnowledgeBaseEntity knowledgeBaseEntity= knowledgeBaseModel.getByKey(importFormDataDTO.getKnowledgeBaseId(),importFormDataDTO.getCorpid());
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_IMPORT_KNOWLEDGE_DATA), userName, knowledgeBaseEntity.getKnowledgeName(), successNum, errorNum);
                    operateModuleTypeEnum = logHelp.getOperateModuleTypeEnum(xbbRefTypeEnum);
                }
            }
            try {
                mongoLogHelp.buildLog(corpid, userId, userName, operateModuleTypeEnum, OperateTypeEnum.IMPORT, "",
                        "", memo, importFormDataDTO.getHttpHeader());
            } catch (XbbException e) {
                LOG.error("导入日志记录出错：", e);
            }
        }
    }

    private void mergeCoverList(String filePrefix,List<ErrorExcelDataPojo> errorList, String formHashKey) throws XbbException {
        try {
            String nowErrorListStr = paasRedisHelper.getValue(filePrefix, formHashKey);
            if(StringUtil.isNotEmpty(nowErrorListStr)){
                JSONArray errorArray = JsonHelperUtil.parseArray(nowErrorListStr);
                if(errorArray.isEmpty()){
                    paasRedisHelper.setValue(filePrefix,formHashKey,errorList, RedisConstant.LONG_DURATION);
                    return;
                }
                List<ErrorExcelDataPojoExt> nowErrorListEtx = errorArray.toJavaList(ErrorExcelDataPojoExt.class);
                if( CollectionsUtil.isNotEmpty(nowErrorListEtx)){
                    List<ErrorExcelDataPojoExt> newErrorList= new ArrayList<>(errorList.size());
                    for (ErrorExcelDataPojo errorExcelDataPojo : errorList) {
                        ErrorExcelDataPojoExt errorExcelDataPojoExt = new ErrorExcelDataPojoExt();
                        BeanUtil.copyProperties(errorExcelDataPojo,errorExcelDataPojoExt);
                        errorExcelDataPojoExt.setRowGroupPojo(errorExcelDataPojo.getRowGroupPojo());
                        newErrorList.add(errorExcelDataPojoExt);
                    }
//                    BeanUtil.copyPropertiesList(errorList,newErrorList,ErrorExcelDataPojoExt.class);
                    nowErrorListEtx.addAll(newErrorList);
                    paasRedisHelper.setValue(filePrefix,formHashKey,nowErrorListEtx, RedisConstant.LONG_DURATION);
                }
            }else{
                paasRedisHelper.setValue(filePrefix,formHashKey,errorList, RedisConstant.LONG_DURATION);
            }
            errorList.clear();
        }    catch ( Exception e) {
            //TODO
            LOG.error("",e);
            throw  new XbbException(SystemErrorCodeEnum.API_ERROR_100055);
        }
    }

    private FormDataAddDTO formatCoverExcelValue(CoverExcelDataPojo coverExcelDataPojo, List<Long> coverDataIdIn) throws XbbException{
        FormDataAddDTO formDataAddDTO = coverExcelDataPojo.getFormDataAddDTO();
        String corpid = formDataAddDTO.getCorpid();
        Integer businessType = formDataAddDTO.getBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        JSONObject dataList = formDataAddDTO.getDataList();
        Long dataId = coverExcelDataPojo.getDataId();
        List<PaasFormDataEntityExt> paasFormDataEntityExts;
        List<String> userOrDeptAttrs = new ArrayList<>();
        List<String> userOrDeptGroupAttrs = new ArrayList<>();
        List<FieldAttrEntityForImport> fieldAttrEntityForImportList = coverExcelDataPojo.getFieldAttrEntityForImportList();
        FieldAttrEntityForImport linkField = null;
        for (FieldAttrEntityForImport field :fieldAttrEntityForImportList) {
            boolean linkAttr  = (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.CONTRACT) && Objects.equals(field.getAttr(), ContractEnum.ADD_PAYMENT.getAttr()))
                    || (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.CUSTOMER_MANAGEMENT) && Objects.equals(field.getAttr(), CustomerManagementEnum.ADD_CONTACT.getAttr()))
                    ||(Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PURCHASE) && Objects.equals(field.getAttr(), PurchaseEnum.ADD_PAYPLAN.getAttr()));
            if (linkAttr) {
                linkField = field;
                break;
            }
        }
        if (Objects.nonNull(linkField)) {
            List<FieldAttrEntityForImport> subExplainList = JSON.parseArray(JSON.toJSONString(linkField.getSubForm().getItems()), FieldAttrEntityForImport.class);
            for (FieldAttrEntityForImport field : subExplainList) {
                if (Objects.equals(field.getFieldType(), FieldTypeEnum.USER.getType()) || Objects.equals(field.getFieldType(), FieldTypeEnum.DEPT.getType())) {
                    userOrDeptAttrs.add(field.getAttr());
                } else if (Objects.equals(field.getFieldType(), FieldTypeEnum.USER_GROUP.getType()) || Objects.equals(field.getFieldType(), FieldTypeEnum.DEPT_GROUP.getType())) {
                    userOrDeptGroupAttrs.add(field.getAttr());
                }
            }
        }
        switch (xbbRefTypeEnum) {
            case CONTRACT:
                if (Objects.nonNull(coverExcelDataPojo.getIsCoverMap()) && coverExcelDataPojo.getIsCoverMap().containsKey(dataId)) {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235035);
                } else {
                    Map<String, List<Long>> productMap = coverExcelDataPojo.getProductMap();
                    JSONArray jsonArray = dataList.getJSONArray(ContractEnum.PRODUCT.getAttr());
                    Integer inStockNum = coverExcelDataPojo.getInStockNum();
                    boolean haveLinkDocument = inStockNum > 0 ? true:false;
                    Set<String> unitKeySet = coverExcelDataPojo.getUnitKey();
                    List<ContractEntityExt> entitysByIdIn = contractModel.findEntitysByIdIn(corpid, BasicConstant.ZERO, coverDataIdIn);
                    Set<Long> productIdSet = new HashSet<>();
                    for (int i = 0; i < jsonArray.size(); i ++) {
                        Long productId = jsonArray.getJSONObject(i).getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(StringConstant.DATA_ID);
                        Object unit = jsonArray.getJSONObject(i).getJSONObject(SelectProductEnum.UNIT.getAttr()).get(StringConstant.VALUE);
                        if (productIdSet.contains(productId)) {
                            continue;
                        } else {
                            productIdSet.add(productId);
                        }
                        String key = dataId + "_" + productId;
                        if (productMap.containsKey(key) && productMap.get(key).size() > 0) {
                            jsonArray.getJSONObject(i).put(BusinessConstant.PRODUCT_SUB_ID, productMap.get(key).get(0));
                        }
                        if (Objects.nonNull(unit) && StringUtil.isDigital(unit.toString()) && Long.parseLong(unit.toString()) > ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                            String unitKey = dataId + "_" + productId + "_" + unit;
                            if (!unitKeySet.contains(unitKey) && haveLinkDocument) {
                                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235053);
                            } else if (!unitKeySet.contains(unitKey)) {
                                for (ContractEntityExt contractEntityExt : entitysByIdIn) {
                                    //校验审批中是否有下游出库单
                                    if (commonHelp.isOpenWorkFlow(corpid)) {
                                        List<PaasFormDataEntityExt> approvalPaasFormDataList = outstockModel.findOutstockList(corpid, OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode(), contractEntityExt.getId(),
                                                Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()), Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                                        if (!approvalPaasFormDataList.isEmpty()) {
                                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235054);
                                        }
                                    } else {
                                        List<PaasProcessRelatedDataEntity> entities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(contractEntityExt.getId(), XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), corpid);
                                        if (!entities.isEmpty()) {
                                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235054);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
                /*JSONArray paymentArr = dataList.getJSONArray(ContractEnum.ADD_PAYMENT.getAttr());
                Map<Long, List<PaasFormDataEntityExt>> paymentMap = coverExcelDataPojo.getPaymentMap();
                paasFormDataEntityExts = paymentMap.get(dataId);
                userOrDeptAttrs.add(PaymentEnum.BELONGER.getAttr());
                if (Objects.nonNull(paymentArr)) {
                    packageLinkDataDeleteData(paasFormDataEntityExts, userOrDeptAttrs, userOrDeptGroupAttrs, paymentArr);
                    for (int i = 0; i < paymentArr.size(); i ++) {
                        JSONObject paymentObj = paymentArr.getJSONObject(i).getJSONObject(StringConstant.JSON_DATA);
                        if  (!Objects.equals(paymentObj.getString(PaymentEnum.STATUS.getAttr()), PaymentStatusEnum.UN_RECEIVABLES.getCode()) && Objects.equals(paymentArr.getJSONObject(i).getInteger(StringConstant.OPERATION_FLAG), LinkAddOperationFlagEnum.DEL.getCode())) {
                            throw new XbbException(ErrorCodeEnum.API_ERROR_235023);
                        }
                    }
                }
                dataList.put(ContractEnum.ADD_PAYMENT.getAttr(), paymentArr);
                */break;
            case PURCHASE:
                if (Objects.nonNull(coverExcelDataPojo.getIsCoverMap()) && coverExcelDataPojo.getIsCoverMap().containsKey(dataId)) {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235035);
                } else {
                    Map<String, List<Long>> productMap = coverExcelDataPojo.getProductMap();
                    Set<String> unitKeySet = coverExcelDataPojo.getUnitKey();
                    JSONArray jsonArray = dataList.getJSONArray(PurchaseEnum.PRODUCT.getAttr());
                    Integer inStockNum = coverExcelDataPojo.getInStockNum();
                    boolean haveLinkDocument = inStockNum > 0 ? true:false;
                    List<PurchaseEntityExt> purchaseListByIdIn = purchaseModel.getPurchaseListByIdIn(corpid, coverDataIdIn);
                    Set<Long> productIdSet = new HashSet<>();
                    for (int i = 0; i < jsonArray.size(); i ++) {
                        Long productId = jsonArray.getJSONObject(i).getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(StringConstant.DATA_ID);
                        Object unit = jsonArray.getJSONObject(i).getJSONObject(SelectProductEnum.UNIT.getAttr()).get(StringConstant.VALUE);
                        if (productIdSet.contains(productId)) {
                            continue;
                        } else {
                            productIdSet.add(productId);
                        }
                        String key = dataId + "_" + productId;
                        if (productMap.containsKey(key) && productMap.get(key).size() > 0) {
                            jsonArray.getJSONObject(i).put(BusinessConstant.PRODUCT_SUB_ID, productMap.get(key).get(0));
                        }
                        if (Objects.nonNull(unit) && StringUtil.isDigital(unit.toString()) && Long.parseLong(unit.toString()) > ProductConstant.MAX_SINGLE_UNIT_VALUE) {
                            String unitKey = dataId + "_" + productId + "_" + unit;
                            if (!unitKeySet.contains(unitKey) && haveLinkDocument) {
                                throw new XbbException(ImportErrorCodeEnum.API_ERROR_235051);
                            } else if (!unitKeySet.contains(unitKey)) {
                                for (PurchaseEntityExt purchaseEntityExt : purchaseListByIdIn) {
                                    //校验审批中是否有下游入库单
                                    if (commonHelp.isOpenWorkFlow(corpid)) {
                                        List<PaasFormDataEntityExt> approvalPaasFormDataList = instockModel.findInstockList(corpid, InstockTypeEnum.PURCHASE_INSTOCK.getCode(), purchaseEntityExt.getId(),
                                                Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()), Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                                        if (!approvalPaasFormDataList.isEmpty()) {
                                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235052);
                                        }
                                    } else {
                                        List<PaasProcessRelatedDataEntity> entities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(purchaseEntityExt.getId(), XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(), corpid);
                                        if (!entities.isEmpty()) {
                                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235052);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                JSONArray payPlanArr = dataList.getJSONArray(PurchaseEnum.ADD_PAYPLAN.getAttr());
                Map<Long, List<PaasFormDataEntityExt>> payPlanMap = coverExcelDataPojo.getPayPlanMap();
                paasFormDataEntityExts = payPlanMap.get(dataId);
                userOrDeptAttrs.add(PayPlanEnum.BELONGER.getAttr());
                if (Objects.nonNull(payPlanArr)) {
                    packageLinkDataDeleteData(paasFormDataEntityExts, userOrDeptAttrs, userOrDeptGroupAttrs, payPlanArr);
                    for (int i = 0; i < payPlanArr.size(); i ++) {
                        JSONObject payPlanObj = payPlanArr.getJSONObject(i).getJSONObject(StringConstant.JSON_DATA);
                        if  (!Objects.equals(payPlanObj.getString(PayPlanEnum.STATUS.getAttr()), PayPlanStatusEnum.UN_RECEIVABLES.getCode()) && Objects.equals(payPlanArr.getJSONObject(i).getInteger(StringConstant.OPERATION_FLAG), LinkAddOperationFlagEnum.DEL.getCode())) {
                            throw new XbbException(ImportErrorCodeEnum.API_ERROR_235024);
                        }
                    }
                }
                dataList.put(PurchaseEnum.ADD_PAYPLAN.getAttr(), payPlanArr);
                break;
            case CUSTOMER_MANAGEMENT:
                JSONArray contactArr = dataList.getJSONArray(CustomerManagementEnum.ADD_CONTACT.getAttr());
                Map<Long, List<PaasFormDataEntityExt>> contactMap = coverExcelDataPojo.getContactMap();
                paasFormDataEntityExts = contactMap.get(dataId);
                if (Objects.nonNull(contactArr) && !contactArr.isEmpty()) {
                    packageLinkDataDeleteData(paasFormDataEntityExts, userOrDeptAttrs, userOrDeptGroupAttrs, contactArr);
                }
                dataList.put(CustomerManagementEnum.ADD_CONTACT.getAttr(), contactArr);
                break;
            case INVENTORY:
            case TRANSFER:
            case PRODUCTION_ORDER:
                if (Objects.nonNull(coverExcelDataPojo.getIsCoverMap()) && coverExcelDataPojo.getIsCoverMap().containsKey(dataId)) {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235035);
                }
                break;
            default:
                break;
        }
       return formDataAddDTO;
    }

    private void packageLinkDataDeleteData(List<PaasFormDataEntityExt> paasFormDataEntityExts, List<String> userOrDeptAttrs, List<String> userOrDeptGroupAttrs, JSONArray linkDataArr) {
        if (Objects.nonNull(paasFormDataEntityExts) && !paasFormDataEntityExts.isEmpty()) {
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExts) {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(paasFormDataEntityExt));
                JSONObject data = jsonObject.getJSONObject(StringConstant.JSON_DATA);
                for (String attr : userOrDeptAttrs) {
                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                    returnUserAndDepartmentPojo.setId(paasFormDataEntityExt.getData().getString(attr));
                    data.put(attr, returnUserAndDepartmentPojo);
                }
                for (String attr : userOrDeptGroupAttrs) {
                    JSONArray arr = paasFormDataEntityExt.getData().getJSONArray(attr);
                    List<ReturnUserAndDepartmentPojo> returnUserAndDepartmentPojoList = new ArrayList<>();
                    if (Objects.nonNull(arr)) {
                        for (Object obj : arr) {
                            ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                            returnUserAndDepartmentPojo.setId(obj.toString());
                            returnUserAndDepartmentPojoList.add(returnUserAndDepartmentPojo);
                        }
                    }
                    data.put(attr, returnUserAndDepartmentPojoList);
                }
                jsonObject.put(StringConstant.OPERATION_FLAG, LinkAddOperationFlagEnum.DEL.getCode());
                linkDataArr.add(jsonObject);
            }
        }
    }
    /**
     *   覆盖导入，获取数据
     *   客户和联系人一起导入时，获取客户下关联的联系人，用于后面删除联系人再次导入Excel中的联系人
     * @param businessType
     * @param corpid
     * @param coverDataIdIn
     * @return
     */
    public CoverExcelDataPojo queryCoverData4Import(Integer businessType, String corpid, List<Long> coverDataIdIn) {
        CoverExcelDataPojo coverExcelDataPojo = new CoverExcelDataPojo();
        String keyword = StringConstant.POINT + StringConstant.KEY_WORD;
        try {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
            boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
            String esData = StringConstant.JSON_DATA + StringConstant.POINT;
            if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
               /* Map<Long, List<PaasFormDataEntityExt>> paymentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                boolQueryBuilder.filter(termsQuery(esData + PaymentEnum.CONTRACT.getAttr() + keyword, coverDataIdIn));
                List<PaasFormDataEntityExt> contractLinkPaymentList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT, boolQueryBuilder, PaasFormDataEntityExt.class, null);
                contractLinkPaymentList.forEach(payment -> {
                    List<PaasFormDataEntityExt> paymentEntityList = new ArrayList<>();
                    Long linkContractId = payment.getData().getLong(PaymentEnum.CONTRACT.getAttr());
                    if (paymentMap.containsKey(linkContractId)) {
                        paymentEntityList.addAll(paymentMap.get(linkContractId));
                    }
                    paymentEntityList.add(payment);
                    paymentMap.put(linkContractId, paymentEntityList);
                });
                coverExcelDataPojo.setPaymentMap(paymentMap);*/
                List<ContractProductEntity> contractProductList = contractProductModel.getContractProductByContractIdIn(corpid, coverDataIdIn);
                Map<Long, List<Long>> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, List<Long>> refIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Set<String> unitKey = new HashSet<>();
                contractProductList.forEach(item -> {
                    List<Long> productIdList = productMap.getOrDefault(item.getContractId(), new ArrayList<>());
                    productIdList.add(item.getProductId());
                    productMap.put(item.getContractId(), productIdList);
                    List<Long> refIdList = refIdMap.getOrDefault(item.getContractId() + "_" + item.getProductId(), new ArrayList<>());
                    refIdList.add(item.getId());
                    refIdMap.put(item.getContractId() + "_" + item.getProductId(), refIdList);
                    if(Objects.isNull(item.getBusinessUnit())){
                        unitKey.add(item.getContractId() + "_" + item.getProductId() + "_" + item.getProductUnit());
                    }else {
                        unitKey.add(item.getContractId() + "_" + item.getProductId() + "_" + item.getBusinessUnit());
                    }
                });
                coverExcelDataPojo.setProductMap(refIdMap);
                coverExcelDataPojo.setUnitKey(unitKey);
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termsQuery(ContractOutstockEnum.getAttrConnectData(ContractOutstockEnum.REF_ID), coverDataIdIn));
                List<PaasFormDataEntityExt> contractOutStockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(ContractOutstockEnum.getAttrConnectData(ContractOutstockEnum.REF_ID)));
                Set<Long> haveRelationSet = new HashSet<>();
                contractOutStockList.forEach(item -> haveRelationSet.add(item.getData().getLong(ContractOutstockEnum.REF_ID.getAttr())));
                Map<Long, Boolean> isCoverMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                coverDataIdIn.forEach(item -> {
                    if (haveRelationSet.contains(item) && productMap.get(item) != null && productMap.get(item).stream().distinct().count() < productMap.get(item).size()) {
                        isCoverMap.put(item, false);
                    }
                });
                coverExcelDataPojo.setIsCoverMap(isCoverMap);
                coverExcelDataPojo.setInStockNum(contractOutStockList.size());
            } else if (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                Map<Long, List<PaasFormDataEntityExt>> payPlanMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                boolQueryBuilder.filter(termsQuery(esData + PayPlanEnum.LINK_PURCHASE.getAttr() + keyword, coverDataIdIn));
                List<PaasFormDataEntityExt> purchaseLinkPayPlanList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAY_PLAN, boolQueryBuilder, PaasFormDataEntityExt.class, null);
                purchaseLinkPayPlanList.forEach(payPlan -> {
                    List<PaasFormDataEntityExt> payPlanEntityList = new ArrayList<>();
                    Long linkPurchaseId = payPlan.getData().getLong(PayPlanEnum.LINK_PURCHASE.getAttr());
                    if (payPlanMap.containsKey(linkPurchaseId)) {
                        payPlanEntityList.addAll(payPlanMap.get(linkPurchaseId));
                    }
                    payPlanEntityList.add(payPlan);
                    payPlanMap.put(linkPurchaseId, payPlanEntityList);
                });
                coverExcelDataPojo.setPayPlanMap(payPlanMap);
                List<PurchaseProductEntity> purchaseProductEntities = purchaseProductModel.getPurchaseProductByPurchaseIdIn(corpid, coverDataIdIn);
                Map<Long, List<Long>> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<String, List<Long>> refIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Set<String> unitKey = new HashSet<>();
                purchaseProductEntities.forEach(item -> {
                    List<Long> productIdList = productMap.getOrDefault(item.getPurchaseSheetId(), new ArrayList<>());
                    productIdList.add(item.getProductId());
                    productMap.put(item.getPurchaseSheetId(), productIdList);
                    List<Long> refIdList = refIdMap.getOrDefault(item.getPurchaseSheetId() + "_" + item.getProductId(), new ArrayList<>());
                    refIdList.add(item.getId());
                    refIdMap.put(item.getPurchaseSheetId() + "_" + item.getProductId(), refIdList);
                    if(Objects.isNull(item.getBusinessUnit())){
                        unitKey.add(item.getPurchaseSheetId() + "_" + item.getProductId() + "_" + item.getProductUnit());
                    }else {
                        unitKey.add(item.getPurchaseSheetId() + "_" + item.getProductId() + "_" + item.getBusinessUnit());
                    }
                });
                coverExcelDataPojo.setProductMap(refIdMap);
                coverExcelDataPojo.setUnitKey(unitKey);
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termsQuery(PurchaseInstockEnum.getAttrConnectData(PurchaseInstockEnum.REF_ID), coverDataIdIn));
                List<PaasFormDataEntityExt> purchaseInStockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(PurchaseInstockEnum.getAttrConnectData(PurchaseInstockEnum.REF_ID)));
                Set<Long> haveRelationSet = new HashSet<>();
                purchaseInStockList.forEach(item -> haveRelationSet.add(item.getData().getLong(PurchaseInstockEnum.REF_ID.getAttr())));
                Map<Long, Boolean> isCoverMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                coverDataIdIn.forEach(item -> {
                    if (haveRelationSet.contains(item) && productMap.get(item) != null && productMap.get(item).stream().distinct().count() < productMap.get(item).size()) {
                        isCoverMap.put(item, false);
                    }
                });
                coverExcelDataPojo.setInStockNum(purchaseInStockList.size());
                coverExcelDataPojo.setIsCoverMap(isCoverMap);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode())) {
                Map<Long, List<PaasFormDataEntityExt>> contactMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                boolQueryBuilder.filter(termsQuery(esData + ContactEnum.CUSTOMER_NAME.getAttr() + keyword, coverDataIdIn));
                List<PaasFormDataEntityExt> customerLinkContactList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT, boolQueryBuilder, PaasFormDataEntityExt.class, null);
                customerLinkContactList.forEach(contact -> {
                    List<PaasFormDataEntityExt> contactList = new ArrayList<>();
                    Long linkCustomerId = contact.getData().getLong(ContactEnum.CUSTOMER_NAME.getAttr());
                    if (contactMap.containsKey(linkCustomerId)) {
                        contactList.addAll(contactMap.get(linkCustomerId));
                    }
                    contactList.add(contact);
                    contactMap.put(linkCustomerId, contactList);
                });
                coverExcelDataPojo.setContactMap(contactMap);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode())) {
                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                if (Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode())) {
                    boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.TYPE),OutstockTypeEnum.INVENTORY_OUTSTOCK.getCode()));
                } else if (Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode())) {
                    boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.TYPE),OutstockTypeEnum.TRANSFER_OUTSTOCK.getCode()));
                } else {
                    boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.TYPE),OutstockTypeEnum.MATERIEL_OUTSTOCK.getCode()));
                }
                boolQueryBuilder.filter(termsQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.REF_ID), coverDataIdIn));
                List<PaasFormDataEntityExt> outStockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_OUTSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(OutstockEnum.getAttrConnectData(OutstockEnum.REF_ID)));
                Set<Long> haveRelationSet = new HashSet<>();
                outStockList.forEach(item -> haveRelationSet.add(item.getData().getLong(OutstockEnum.REF_ID.getAttr())));
                Map<Long, Boolean> isCoverMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                coverDataIdIn.forEach(item -> {
                    if (haveRelationSet.contains(item)) {
                        isCoverMap.put(item, false);
                    }
                });

                boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + keyword, corpid));
                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                if (Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode())) {
                    boolQueryBuilder.filter(termQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.TYPE),InstockTypeEnum.INVENTORY_INSTOCK.getCode()));
                } else if (Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode())) {
                    boolQueryBuilder.filter(termQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.TYPE),InstockTypeEnum.TRANSFER_INSTOCK.getCode()));
                } else {
                    boolQueryBuilder.filter(termQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.TYPE),InstockTypeEnum.FINSHED_PRODUCT_INSTOCK.getCode()));
                }
                boolQueryBuilder.filter(termsQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.REF_ID), coverDataIdIn));
                List<PaasFormDataEntityExt> instockList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INSTOCK, boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(InstockEnum.getAttrConnectData(InstockEnum.REF_ID)));
                haveRelationSet.clear();
                instockList.forEach(item -> haveRelationSet.add(item.getData().getLong(InstockEnum.REF_ID.getAttr())));
                coverDataIdIn.forEach(item -> {
                    if (haveRelationSet.contains(item)) {
                        isCoverMap.put(item, false);
                    }
                });

                coverExcelDataPojo.setIsCoverMap(isCoverMap);
            }
        } catch (Exception e) {
            LOG.error("导入数据异常", e);
        }
        return coverExcelDataPojo;
    }

    /**
     * 查重，返回是否可以继续导入
     *
     * @param importFormDataDTO       导入入参
     * @param importStatusPojo        导入状态
     * @param errorList               错误数据
     * @param updateList              重复数据
     * @param repeatRowGroupPojoList  重复数据覆盖导入用
     * @param noRepeatAttrNameList    需要查重的attr列表
     * @param noRepeatAttrNameMap
     * @param rowGroupPojo            当前数据
     * @param repeatQuotationValueMap 报价单编号
     * @param explainMap
     * @param dataList
     * @return 是否可以继续导入
     * @throws XbbException xbbException
     */
    private boolean checkRepeat(ImportFormDataDTO importFormDataDTO, ImportStatusPojo importStatusPojo, List<ErrorExcelDataPojo> errorList, List<ErrorExcelDataPojo> updateList, List<ErrorExcelDataPojo> noSignPersonList, List<RowGroupPojo> repeatRowGroupPojoList, List<String> noRepeatAttrNameList, Map<String, String> noRepeatAttrNameMap, RowGroupPojo rowGroupPojo, Map<String,Object> repeatQuotationValueMap, Map<String, FieldAttrEntity> explainMap, JSONObject dataList) throws XbbException {
        if (noRepeatAttrNameList.isEmpty()) {
            // 没有查重字段，继续导入
            return true;
        }
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        if (rowValueList.isEmpty()) {
            return true;
        }
        // 查重字段-值map
        Map<String,Object> repeatValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<CellValuePojo> cellValuePojoList = rowValueList.get(0);
        for (CellValuePojo cellValuePojo : cellValuePojoList) {
            String parentTitle = cellValuePojo.getParentTitle();
            String title = cellValuePojo.getTitle();
            if (Objects.nonNull(parentTitle)) {
                title = parentTitle + StringConstant.COMMA + title;
            }
            // 处理判重为成员单选等特殊字段数据判重，不从Excel的数据中获取
            // TODO: 2022/5/7 这边目前没有做子表单内数据的判重
            if (noRepeatAttrNameList.contains(title)) {
                Object value = cellValuePojo.getValue();
                String attr = noRepeatAttrNameMap.get(title);
                if (Objects.nonNull(value) && StringUtil.isNotEmpty(value.toString())) {
                    FieldAttrEntity fieldAttrEntity = explainMap.get(attr);
                    if (Objects.nonNull(fieldAttrEntity)) {
                        if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.USER.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.DEPT.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.DEPARTMENTID.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.CREATORID.getType())) {
                            if (Objects.nonNull(dataList.get(attr))) {
                                value = dataList.get(attr);
                                JSONObject jsonObject = (JSONObject) value;
                                value = jsonObject.get(ParameterConstant.ID);
                            }
                        }
                    }
                    repeatValueMap.put(attr, value);
                }
            }
        }
        repeatValueMap.putAll(repeatQuotationValueMap);
        FormDataRepeatDTO formDataRepeatDTO = new FormDataRepeatDTO();
        BeanUtil.copyProperties(importFormDataDTO,formDataRepeatDTO);
        FormDataRepeatVO formDataRepeatVO;
        if (Objects.equals(formDataRepeatDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
            formDataRepeatVO = priceSetService.importRepeat(formDataRepeatDTO, repeatValueMap);
        } else {
            formDataRepeatVO = paasFormDataService.repeat(formDataRepeatDTO,repeatValueMap);
        }
        if (formDataRepeatVO.getFormDataList().size() > 1) {
            XbbException xbbException = new XbbException(SystemErrorCodeEnum.API_ERROR_100018, ErrorMessageConstant.DUPLICATE_DATA_SYSTEM);
            putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
            return false;
        } else if (formDataRepeatVO.getFormDataList().size() == 1) {
            if (Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE_INSTOCK.getCode()) || Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())
                || Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode()) || Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())
                || Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.ASSEMBLE.getCode()) || Objects.equals(importFormDataDTO.getBusinessType(), XbbRefTypeEnum.ORI_STOCK.getCode())) {
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(importFormDataDTO.getBusinessType());
                XbbException xbbException = new XbbException(SystemErrorCodeEnum.API_ERROR_100018, ErrorMessageConstant.EXISTS_SYSTEM, xbbRefTypeEnum.getName());
                putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                return false;
            }
            PaasFormDataEntityExt paasFormDataEntityExt = formDataRepeatVO.getFormDataList().get(0);
            if (paasFormDataEntityExt != null) {
                Integer flowStatus = paasFormDataEntityExt.getFlowStatus();
                // 是否审批中数据
                boolean isApprovalData = Objects.equals(flowStatus, FlowStatusEnum.APPROVAL_PENDING.getType()) || Objects.equals(flowStatus, FlowStatusEnum.IN_APPROVAL.getType());
                if (isApprovalData) {
                    XbbException xbbException = new XbbException(SystemErrorCodeEnum.API_ERROR_100018, ErrorMessageConstant.DUPLICATE_DATA_APPROVAL);
                    putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                    return false;
                } else {
                    XbbException xbbException = new XbbException(SystemErrorCodeEnum.API_ERROR_100034);
                    if (Objects.equals(importFormDataDTO.getFormId(),paasFormDataEntityExt.getFormId())) {
                        rowGroupPojo.setDataId(paasFormDataEntityExt.getDataId());
                        putToErrorList(errorList, updateList, noSignPersonList, rowGroupPojo, xbbException, importStatusPojo);
                        repeatRowGroupPojoList.add(rowGroupPojo);
                    } else {
                        xbbException = new XbbException(SystemErrorCodeEnum.API_ERROR_100018, ErrorMessageConstant.DUPLICATE_DATA_SYSTEM);
                        putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                    }

                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Description: 检查导入的是否是历史版本
     * @param importFormDataDTO
     * @param groupNumberValue
     * @param versionValue
     * @return Boolean
     * @throws XbbException
     * @author 刘阳
     * @date 2019/10/22 11:28 AM
     * @since 1.0
     */
    private Boolean checkQuotation(ImportFormDataDTO importFormDataDTO, Object groupNumberValue, Object versionValue, ImportStatusPojo importStatusPojo, List<ErrorExcelDataPojo> errorList,List<ErrorExcelDataPojo> updateList, List<ErrorExcelDataPojo> noSignPersonList, RowGroupPojo rowGroupPojo) throws XbbException {
        String groupNumber = groupNumberValue.toString();
        String version = versionValue.toString();
        if (!version.matches(RegExConstant.QUOTATION_VERSION)) {
            if (version.matches(RegExConstant.QUOTATION_INTFER)) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(version);
                stringBuilder.append(".0");
                version = stringBuilder.toString();
            } else {
                XbbException xbbException = new XbbException(QuotationErrorCodeEnum.API_ERROR_246007, ErrorMessageConstant.VERSION_NUMBER_ERROR);
                putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                return false;
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(groupNumber);
        stringBuilder.append(version);
        String serialNo = stringBuilder.toString();
        BoolQueryBuilder filter = boolQuery()
                .filter(termQuery("corpid" + StringConstant.POINT + StringConstant.KEY_WORD, importFormDataDTO.getCorpid()))
                .filter(termQuery("del", 0))
                .filter(termQuery("data." + QuotationEnum.GROUP_NUMBER.getAttr() + StringConstant.POINT + StringConstant.KEY_WORD, groupNumber))
                .filter(termQuery("data." + QuotationEnum.IS_NEW.getAttr(), BasicConstant.ONE))
                .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(QuotationEnum.getAttrConnectData(QuotationEnum.VERSION));
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_QUOTATION, filter, PaasFormDataEntityExt.class, fieldList, BasicConstant.ONE, BasicConstant.ONE, null);
        if (esEntities == null || esEntities.getContent().isEmpty()) {
            if (version.matches(BasicConstant.EDTATION.toString())) {
                return true;
            } else {
                XbbException xbbException = new XbbException(QuotationErrorCodeEnum.API_ERROR_246004, ErrorMessageConstant.QUOTATION_VERSION_NUMBER_ERROR);
                putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                return false;
            }
        } else {
            JSONObject data = esEntities.getContent().get(BasicConstant.ZERO).getData();
            Object isNewVersion = data.get(QuotationEnum.VERSION.getAttr());
            Double versionD = Double.parseDouble(version);
            Double isNewVersionD = Double.parseDouble(isNewVersion.toString());
            if (versionD < isNewVersionD) {
                XbbException xbbException = new XbbException(QuotationErrorCodeEnum.API_ERROR_246008);
                putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                return false;
            }
        }
        return true;
    }

    /**
     * Description: 校验报价单名称（防重复开启的情况）
     * @param importFormDataDTO
     * @param versionValue
     * @param noRepeatAttrNameList
     * @param noRepeatAttrNameMap
     * @return Boolean
     * @throws XbbException
     * @author 刘阳
     * @date 2019/10/29 4:56 PM
     * @since v1.0
     */
    private Boolean checkNewQuotationName(ImportFormDataDTO importFormDataDTO, Object groupNumberValue, Object versionValue, List<String> noRepeatAttrNameList, Map<String, String> noRepeatAttrNameMap, ImportStatusPojo importStatusPojo, List<ErrorExcelDataPojo> errorList,List<ErrorExcelDataPojo> updateList, List<ErrorExcelDataPojo> noSignPersonList, RowGroupPojo rowGroupPojo, Object nameValue, List<FieldAttrEntityForImport> fieldAttrEntityForImportList) throws XbbException {
        String version = versionValue.toString();
        String groupNumber =  groupNumberValue.toString();
        if (!version.matches(RegExConstant.QUOTATION_VERSION)) {
            if (version.matches(RegExConstant.QUOTATION_INTFER)) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(version);
                stringBuilder.append(".0");
                version = stringBuilder.toString();
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(groupNumber);
        stringBuilder.append(version);
        String serialNo = stringBuilder.toString();
        String quotationName = "";
        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrEntityForImportList) {
            if (Objects.equals(fieldAttrEntityForImport.getAttr(), QuotationEnum.NAME.getAttr())) {
                quotationName = fieldAttrEntityForImport.getAttrName();
            }
        }
        if (version.matches(BasicConstant.EDTATION.toString()) && (noRepeatAttrNameList.contains(quotationName) || noRepeatAttrNameList.contains(quotationName + StringConstant.SPECIALMODEL))) {
            String name = Objects.toString(nameValue, "");
            BoolQueryBuilder filter = boolQuery()
                    .filter(termQuery("corpid" + StringConstant.POINT + StringConstant.KEY_WORD, importFormDataDTO.getCorpid()))
                    .filter(termQuery("del", 0))
                    .filter(termQuery("data." + QuotationEnum.NAME.getAttr() + StringConstant.POINT + StringConstant.KEY_WORD, name))
                    .filter(termQuery("data." + QuotationEnum.IS_NEW.getAttr(), BasicConstant.ONE))
                    .filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
            List<PaasFormDataEntityExt> esEntities = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_QUOTATION, filter, PaasFormDataEntityExt.class, Arrays.asList(FieldTypeEnum.SERIALNO.getAlias()));
            if (esEntities.size() > 0) {
                for (PaasFormDataEntityExt entityExt : esEntities) {
                    if (Objects.equals(entityExt.getSerialNo(), serialNo)) {
                        return true;
                    }
                }
                XbbException xbbException = new XbbException(QuotationErrorCodeEnum.API_ERROR_246012);
                putToErrorList(errorList,updateList,noSignPersonList,rowGroupPojo,xbbException,importStatusPojo);
                return false;
            }
        }
        return true;
    }

    /**
     * 关联客户模拟成子表单，电话和姓名可选填一个，也可都填，来进行客户判重
     *
     * @param item 解释
     */
    private void setLinkCustomerToSubForm(FieldAttrEntityForImport item) {
        List<FieldAttrEntity> subFormFieldAttrList = new ArrayList<>();
        FieldAttrEntity nameFieldAttrEntity = new FieldAttrEntity();
        nameFieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
        BeanUtil.copyProperties(ImportEnum.LINK_CUSTOMER_NAME, nameFieldAttrEntity);
        subFormFieldAttrList.add(nameFieldAttrEntity);

        FieldAttrEntity phoneFieldAttrEntity = new FieldAttrEntity();
        BeanUtil.copyProperties(ImportEnum.LINK_CUSTOMER_PHONE, phoneFieldAttrEntity);
        phoneFieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
        subFormFieldAttrList.add(phoneFieldAttrEntity);

        SubFormPoJo subFormPoJo = new SubFormPoJo();
        subFormPoJo.setItems(subFormFieldAttrList);
        item.setSubForm(subFormPoJo);
        item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
    }

    /**
     * 将特殊字段设置为子表单类型
     *
     * @param item   解释
     * @param fieldList         子表单字段
     */
    private void setSpecialFields2SubForm(FieldAttrEntityForImport item, List fieldList) {
        List<FieldAttrEntity> subFormFieldAttrList = new ArrayList<>();
        for (Object field : fieldList) {
            FieldAttrEntity subFormFieldAttrEntity = new FieldAttrEntity();
            BeanUtil.copyProperties(field, subFormFieldAttrEntity);
            subFormFieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
            subFormFieldAttrList.add(subFormFieldAttrEntity);
        }
        SubFormPoJo subFormPoJo = new SubFormPoJo();
        subFormPoJo.setItems(subFormFieldAttrList);
        item.setSubForm(subFormPoJo);
        item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
    }

    /**
     * 将特殊必填字段设置为子表单类型
     *
     * @param item   解释
     * @param fieldList         子表单字段
     */
    private void setSpecialRequiredFields2SubForm(FieldAttrEntityForImport item, List fieldList) {
        List<FieldAttrEntity> subFormFieldAttrList = new ArrayList<>();
        for (Object field : fieldList) {
            FieldAttrEntity subFormFieldAttrEntity = new FieldAttrEntity();
            BeanUtil.copyProperties(field, subFormFieldAttrEntity);
            subFormFieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
            if (Objects.equals(item.getRequired(), 1)) {
                subFormFieldAttrEntity.setRequired(1);
            }
            subFormFieldAttrList.add(subFormFieldAttrEntity);
        }
        SubFormPoJo subFormPoJo = new SubFormPoJo();
        subFormPoJo.setItems(subFormFieldAttrList);
        item.setSubForm(subFormPoJo);
        item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
    }

    /**
     * 将特殊字段设置为子表单类型
     *
     * @param item   解释
     */
    private void setBirthdayToSubForm(FieldAttrEntityForImport item) {
        List<FieldAttrEntity> subFormFieldAttrList = new ArrayList<>();
        FieldAttrEntity birthdayTypeFieldAttrEntity = new FieldAttrEntity();
        BeanUtil.copyProperties(ImportEnum.BIRTHDAY_FLAG, birthdayTypeFieldAttrEntity);
        List<ItemPoJo> itemPoJos = new ArrayList<>();
        for (BirthdayTypeEnum birthdayTypeEnum : BirthdayTypeEnum.values()) {
            ItemPoJo itemPoJo = new ItemPoJo();
            BeanUtil.copyProperties(birthdayTypeEnum, itemPoJo);
            itemPoJos.add(itemPoJo);
        }
        birthdayTypeFieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
        birthdayTypeFieldAttrEntity.setFieldType(FieldTypeEnum.COMBO.getType());
        birthdayTypeFieldAttrEntity.setItems(itemPoJos);
        birthdayTypeFieldAttrEntity.setComboType(ComboTypeEnum.CUSTOM.getType());
        subFormFieldAttrList.add(birthdayTypeFieldAttrEntity);

        FieldAttrEntity birthdayFieldAttrEntity = new FieldAttrEntity();
        BeanUtil.copyProperties(ImportEnum.BIRTHDAY, birthdayFieldAttrEntity);
        birthdayFieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
        birthdayFieldAttrEntity.setFieldType(FieldTypeEnum.DATETIME.getType());
        birthdayFieldAttrEntity.setDateType(DateTimeEnum.TIME.getType());
        subFormFieldAttrList.add(birthdayFieldAttrEntity);

        SubFormPoJo subFormPoJo = new SubFormPoJo();
        subFormPoJo.setItems(subFormFieldAttrList);
        item.setSubForm(subFormPoJo);
        item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList,
                                           RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList, String contactLabelAttr, Map<String, JSONObject> contactLabelPojoMap) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        formDataAddDTO.setSerialNo("");
        Integer businessType = XbbRefTypeEnum.transferBusinessType4Distributor(importFormDataDTO.getBusinessType(), importFormDataDTO.getDistributorMark());
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case SUPPLIER:
                formDataAddDTO = supplierService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CONTRACT:
                formDataAddDTO = contractService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case ORDER:
                formDataAddDTO = orderService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CONTACT:
            case DISTRIBUTOR_CONTACT:
                formDataAddDTO = contactService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case BOM_BILL:
                formDataAddDTO = bomBillService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PRODUCTION_ORDER:
                formDataAddDTO = productionOrderService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case SUPPLIER_CONTACT:
                formDataAddDTO = supplierContactService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case OTHER_INSTOCK:
                formDataAddDTO = instockService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case ORDER_OUTSTOCK:
                formDataAddDTO = outstockService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PRODUCT:
                formDataAddDTO = productService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CUSTOMER_COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
                List<CellValuePojo> cellValueList = rowValueList.get(0);
                boolean isClue = false;
                for (CellValuePojo cellValuePojo : cellValueList) {
                    String title = cellValuePojo.getTitle();
                    Object value = cellValuePojo.getValue();
                    if (StringUtil.isNotEmpty(title) && Objects.equals(title, ImportEnum.COMMUNICATE_BUSINESS_TYPE.getAttrName()) && Objects.equals(value, XbbRefTypeEnum.CLUE.getName())){
                        isClue = true;
                        break;
                    }
                }
                if (!isClue){
                    formDataAddDTO = customerCommunicateService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                } else {
                    formDataAddDTO = customerCommunicateService.formatClueExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                }

                break;
            case SUPPLIER_COMMUNICATE:
                formDataAddDTO = supplierCommunicateService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CUSTOMER_MANAGEMENT:
                formDataAddDTO = customerService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList, contactLabelAttr, contactLabelPojoMap);
                break;
            case DISTRIBUTOR_MANAGEMENT:
                formDataAddDTO = distributorManageService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case SALES_OPPORTUNITY:
                formDataAddDTO = opportunityService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case INVENTORY:
                formDataAddDTO = inventoryService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case TRANSFER:
                formDataAddDTO = transferService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case ASSEMBLE:
                formDataAddDTO = assembleService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case RETURNED_PURCHASE:
                formDataAddDTO = returnedPurchaseService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PURCHASE:
                formDataAddDTO = purchaseService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case INVOICE:
                formDataAddDTO = invoiceService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PURCHASE_INVOICE:
                formDataAddDTO = purchaseInvoiceService.formatExcelValue(importFormDataDTO,titlePojoList,rowGroupPojo,fieldAttrList);
                break;
            case REFUND:
                formDataAddDTO = refundService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case WORK_ORDER:
                formDataAddDTO = workOrderService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case SYSTEM:
                formDataAddDTO = formatPaasExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PAYMENT:
                /**
                 * 资金管理1期改造，新增应收款的导入功能，后续还未调试通过导入接口
                 * @author chenshan
                 * @Date 2019-11-05 9:41
                 */
                formDataAddDTO = paymentService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case QUOTATION:
                formDataAddDTO = quotationService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PAYMENT_SHEET:
                formDataAddDTO = paymentSheetService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PAY_SHEET:
                formDataAddDTO = payPlanSheetService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PAY_PLAN:
                formDataAddDTO = payPlanService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case ORI_STOCK:
                formDataAddDTO = oriStockService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CREDIT_LIMIT:
                formDataAddDTO = creditLimitService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CREDIT_TEMPORARY_LIMIT:
                formDataAddDTO = creditTemporaryLimitService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CREDIT_FIXED_LIMIT:
                formDataAddDTO = creditFixedLimitService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case PRICE_SET_PRODUCT:
                formDataAddDTO = priceSetService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case CLUE:
                formDataAddDTO = clueService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case MARKET_ACTIVITY:
                formDataAddDTO = marketActivityService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case DISTRIBUTOR_ACCOUNT:
                formDataAddDTO = distributorAccountService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case FUND_TRANSFER:
                formDataAddDTO = fundTransferService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case OTHER_INCOME:
                formDataAddDTO = otherIncomeService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case OTHER_EXPENSE:
                formDataAddDTO = otherExpenseService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case COST_ADJUST:
                formDataAddDTO = costAdjustService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case KNOWLEDGE_BASE:
                formDataAddDTO = knowledgeDataService.formatExcelValue(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case WORK_ORDER_V2:
                formDataAddDTO = workOrderV2ImportHelp.formatExcelValue4WorkOrderV2(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);
                break;
            case SERVICE_PROJECT:
                formDataAddDTO = workOrderV2ImportHelp.formatExcelValue4ServiceProject(importFormDataDTO, titlePojoList, rowGroupPojo, fieldAttrList);

                break;
            case COMPETITOR:
                formDataAddDTO = competitorService.formatExcelValue(importFormDataDTO,titlePojoList,rowGroupPojo,fieldAttrList);
                break;
            default:
                break;
        }
        return formDataAddDTO;
    }

    private FormDataAddDTO formatPaasExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        formDataAddDTO.setSerialNo("");
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        // data 数据
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);

        // 遍历数据
        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
            String attr = fieldAttrEntityForImport.getAttr();
            Integer fieldType = fieldAttrEntityForImport.getFieldType();
            String attrName = fieldAttrEntityForImport.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);

            if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttrEntityForImport, dataJson);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                formDataAddDTO.setSerialNo(cellValue.toString());
            //处理关联数据
            }else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())){
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                importHelper.formatLinkData(cellValue, fieldAttrEntityForImport, dataJson);
            }else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())){
                if(Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())){
                    continue;
                }
                importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttrEntityForImport, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttrEntityForImport.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttrEntityForImport, cellValue);
                } else {
                    dataJson.put(attr, cellValue);
                }
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public void formatExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum;
        if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())
                || Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_PURCHASE.getCode())
                || Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())
                || Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())){
            xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getSubBusinessType());
        }else{
            xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getBusinessType());
        }
        switch (xbbRefTypeEnum) {
            case CONTRACT:
            case ORDER:
                contractService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList, formDataListDTO.getBusinessType());
                break;
            case CUSTOMER_MANAGEMENT:
                customerService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList, formDataListDTO.getBusinessType());
                break;
            case DISTRIBUTOR_MANAGEMENT:
                distributorManageService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList, formDataListDTO.getBusinessType());
                break;
            case CLUE:
                clueService.formatExportValue(paasFormDataESList, fieldAttrList);
                break;
            case SALES_OPPORTUNITY:
                opportunityService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case SUPPLIER:
                supplierService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case INSTOCK:
            case OTHER_INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                instockService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case OUTSTOCK:
            case OTHER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                outstockService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case ASSEMBLE:
                assembleService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case TRANSFER:
                transferService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case INVENTORY:
                inventoryService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case PURCHASE:
                purchaseService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList, formDataListDTO.getBusinessType());
                break;
            case RETURNED_PURCHASE:
                returnedPurchaseService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case INVOICE:
                invoiceService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case PURCHASE_INVOICE:
                purchaseInvoiceService.formatExportValue(paasFormDataESList,formDataListDTO,fieldAttrList);
                break;
            case BOM_BILL:
                bomBillService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case PRODUCTION_ORDER:
                productionOrderService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case PRODUCT:
                if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                    productService.formatStockSearchExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                } else if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
                    productService.formatWarningSearchExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                } else if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                    productService.formatGuaranteeSearchExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                } else {
                    productService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                }
                break;
            case REFUND:
            case RETURN:
                refundService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case WORK_ORDER:
                workOrderService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case QUOTATION:
                quotationService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case SEQ_SEARCH:
                productSerialService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case PRICE_SET_PRODUCT:
                priceSetService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case PROMOTION_ACTIVITY_MANAGEMENT:
                promotionActivityService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case COST_ADJUST:
                costAdjustService.formatExportValue(paasFormDataESList, formDataListDTO, fieldAttrList);
                break;
            case WAIT_INSTOCK_PURCHASE:
                if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE.getCode())){
                    purchaseService.formatWaitInstockPurchaseExportValue(paasFormDataESList, formDataListDTO);
                }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                    productService.formatWaitInstockProductExportValue(paasFormDataESList, formDataListDTO);
                }
                break;
            case WAIT_OUTSTOCK:
                if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
                    contractService.formatWaitOutstockContractExportValue(paasFormDataESList, formDataListDTO);
                }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                    productService.formatWaitOutstockProductExportValue(paasFormDataESList, formDataListDTO);
                }
                break;
            case WAIT_PURCHASE:
                if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
                    contractService.formatWaitPurchaseExportValue(paasFormDataESList, formDataListDTO);
                }else if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                    productService.formatWaitPurchaseProductExportValue(paasFormDataESList, formDataListDTO);
                }
                break;
            case RECEIPT_ORDER:
            case SERVICE_PROJECT:
                try {
                    ExportFormatValueDTO exportFormatValueDTO = new ExportFormatValueDTO();
                    BeanUtil.copyProperties(formDataListDTO,exportFormatValueDTO);
                    exportFormatValueDTO.setPaasFormDataESList(paasFormDataESList);
                    exportFormatValueDTO.setFieldAttrList(fieldAttrList);
                    exportFormatValueDTO.setFormDataListDTO(formDataListDTO);
                    String formatExportValue = workOrderImportClient.formatExportValue(exportFormatValueDTO, LocaleContextHolder.getLocale().toString());
                    JSONObject resultObj = JsonHelperUtil.parseObject(formatExportValue);
                    if (ErrorCodeEnum.API_SUCCESS.getCode() != (int)resultObj.get(StringConstant.CODE)) {
                        throw new XbbException(resultObj.getIntValue(StringConstant.CODE),resultObj.getString(StringConstant.KEY_ERROR_MSG));
                    }
                    ExportFormatValueVO formatValueVO = JsonHelperUtil.parseObject(resultObj.getString("result"), ExportFormatValueVO.class);
                    paasFormDataESList.clear();
                    paasFormDataESList.addAll(formatValueVO.getPaasFormDataESList());
                    fieldAttrList.clear();
                    fieldAttrList.addAll(formatValueVO.getFieldAttrList());
                    formDataListDTO = formatValueVO.getFormDataListDTO();
                    break;
                } catch (Exception e) {
                    LOG.error("获取表单数据报错", e);
                    break;
                }
            case SMART_REPLENISHMENT:
                productService.formatSmartReplenishmentExportValue(paasFormDataESList, formDataListDTO);
                break;
            case WORK_ORDER_V2:
                workOrderV2ImportHelp.formatWorkOrderV2ExportValue(paasFormDataESList, formDataListDTO);
                break;
            default:
                break;
        }
    }



    /**
     * 将仓库改成下拉框
     * @param item
     * @param warehouseListVO
     */
    private void setWareHouseToCombo(FieldAttrEntity item, WarehouseListVO warehouseListVO) {
        item.setFieldType(FieldTypeEnum.COMBO.getType());
        List<ItemPoJo> itemPoJoList = new ArrayList<>();
        /*WarehouseListDTO warehouseListDTO = new WarehouseListDTO();
        BeanUtil.copyProperties(excelTemplateDTO, warehouseListDTO);
        WarehouseListVO warehouseListVO = warehouseService.getManagetWarehouses(warehouseListDTO);*/
        for (WarehouseEntityExt warehouseEntityExt : warehouseListVO.getWarehouseList()) {
            JSONObject data = warehouseEntityExt.getData();
            String name = data.getString(WarehouseEnum.WAREHOUSE_NAME.getAttr());
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setText(name);
            itemPoJo.setValue(warehouseEntityExt.getId());
            itemPoJoList.add(itemPoJo);
        }
        item.setItems(itemPoJoList);
    }

    /**
     * 将仓库改成下拉框
     * @param item
     * @param excelTemplateDTO
     */
    private void setOriStockWareHouseToCombo(FieldAttrEntity item, ExcelTemplateDTO excelTemplateDTO) throws XbbException{
        item.setFieldType(FieldTypeEnum.COMBO.getType());
        List<ItemPoJo> itemPoJoList = new ArrayList<>();
        UserVO loginUser = excelTemplateDTO.getLoginUser();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID, excelTemplateDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(WarehouseEnum.getEsAttr4Keyword(WarehouseEnum.ORI_STOCK), WarehouseOriStockEnum.NOT_DONE.getCode()));
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(loginUser, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity, SaasMarkEnum.SAAS, XbbRefTypeEnum.WAREHOUSE.getCode(), null);
        if (!(dataPermission != null && dataPermission.equals(5))){
            List<List<ConditionsEntityExt>> shouldConditionList = new ArrayList<>();
            saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditionList, loginUser, XbbRefTypeEnum.WAREHOUSE.getCode(), loginUser.getDepSet());
            EsUtil.parseShouldCondition(boolQueryBuilder,shouldConditionList,"",excelTemplateDTO.getCorpid(),XbbRefTypeEnum.WAREHOUSE.getCode());
        }
        List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_WAREHOUSE,boolQueryBuilder,PaasFormDataEntityExt.class,
                Arrays.asList(WarehouseEnum.getAttrConnectData(WarehouseEnum.WAREHOUSE_NAME), StringConstant.SAAS_LINK_BUSINESS_ID));
        for (PaasFormDataEntityExt warehouseEntityExt : paasFormDataEntityExtList) {
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setText(warehouseEntityExt.getData().getString(WarehouseEnum.WAREHOUSE_NAME.getAttr()));
            itemPoJo.setValue(warehouseEntityExt.getId());
            itemPoJoList.add(itemPoJo);
        }
        item.setItems(itemPoJoList);
    }

    /**
     * 将供应商改成下拉框
     * @param item
     * @param excelTemplateDTO
     */
    private void setSupplierToCombo(FieldAttrEntity item, ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        item.setFieldType(FieldTypeEnum.COMBO.getType());
        List<ItemPoJo> itemPoJoList = new ArrayList<>();
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid", excelTemplateDTO.getCorpid());
        params.put("del", 0);
        List<SupplierEntityExt> supplierEntityList = supplierModel.findEntitys(params);
        for (SupplierEntityExt supplierEntity : supplierEntityList) {
            JSONObject data = supplierEntity.getData();
            String name = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, supplierEntity.getId());
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME, name);
            jsonArray.add(jsonObject);
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setText(name);
            itemPoJo.setValue(jsonArray);
            itemPoJoList.add(itemPoJo);
        }
        item.setItems(itemPoJoList);
    }

    /**
     * 将库存改为子表单，子表单项为仓库列表
     * @param item
     * @param excelTemplateDTO
     */
    private void setWareHouseToStock(FieldAttrEntityForImport item, ExcelTemplateDTO excelTemplateDTO) {
        JSONArray jsonArray = warehouseModel.getWarehouseArray(excelTemplateDTO.getCorpid());
        if (jsonArray.isEmpty()) {
           return;
        }
        item.setFieldType(FieldTypeEnum.SUB_FORM.getType());
        item.setNeedImportSeparately(ImportConstant.NEED_IMPORT_SEPARATELY);
        SubFormPoJo subFormPoJo = new SubFormPoJo();
        List<FieldAttrEntityForImport> items = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String warehouseName = jsonObject.getString("warehouseName");
            String warehouseId = jsonObject.getString("warehouseId");
            FieldAttrEntityForImport fieldAttrEntityForImport = new FieldAttrEntityForImport();
            fieldAttrEntityForImport.setFieldType(FieldTypeEnum.TEXT.getType());
            fieldAttrEntityForImport.setAttr(warehouseId);
            fieldAttrEntityForImport.setAttrName(warehouseName);
            items.add(fieldAttrEntityForImport);
        }
        subFormPoJo.setItems(items);
        item.setSubForm(subFormPoJo);
    }

    /**
     * 入库单关联单据map
     * @param item
     * @param excelTemplateDTO
     * @throws XbbException
     */
    private void setRefSheet(FieldAttrEntityForImport item, ExcelTemplateDTO excelTemplateDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        Map<String, Object> stockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(item.getAttr(), InstockEnum.REF_ID.getAttr())) {
            FieldAttrEntityForImport refType = new FieldAttrEntityForImport();
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                if (Objects.equals(fieldAttrEntityForImport.getAttr(), InstockEnum.TYPE.getAttr())) {
                    refType = fieldAttrEntityForImport;
                }
            }
            List<ItemPoJo> itemPoJoList = refType.getItems();
            for (ItemPoJo itemPoJo : itemPoJoList) {
                Integer code = Integer.valueOf(itemPoJo.getValue().toString());
                InstockTypeEnum instockTypeEnum = InstockTypeEnum.getByCode(code);
                if (Objects.equals(instockTypeEnum, InstockTypeEnum.OTHER_INSTOCK) || Objects.equals(instockTypeEnum, InstockTypeEnum.ASSEMBLE_INSTOCK)) {
                    continue;
                }
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(instockTypeEnum.getBusinessType(), excelTemplateDTO.getCorpid(), excelTemplateDTO.getDistributorMark(), null);
                BusinessDataDTO businessDataDTO = new BusinessDataDTO();
                BeanUtil.copyProperties(excelTemplateDTO, businessDataDTO);
                businessDataDTO.setPageSize(10000);
                businessDataDTO.setSourceBusinessType(excelTemplateDTO.getBusinessType());
                businessDataDTO.setFormId(paasFormEntityExt.getId());
                businessDataDTO.setBusinessType(instockTypeEnum.getBusinessType());
                businessDataDTO.setType(instockTypeEnum.getCode());
                PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.getBusinessDataList(businessDataDTO);
                stockMap.put(itemPoJo.getValue().toString(), paasFormDataEsListVO);
            }
        } else if (Objects.equals(item.getAttr(), OutstockEnum.REF_ID.getAttr())) {
            FieldAttrEntityForImport refType = new FieldAttrEntityForImport();
            for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
                if (Objects.equals(fieldAttrEntityForImport.getAttr(), OutstockEnum.TYPE.getAttr())) {
                    refType = fieldAttrEntityForImport;
                }
            }
            List<ItemPoJo> itemPoJoList = refType.getItems();
            for (ItemPoJo itemPoJo : itemPoJoList) {
                Integer code = Integer.valueOf(itemPoJo.getValue().toString());
                OutstockTypeEnum outstockTypeEnum = OutstockTypeEnum.getByCode(code);
                if (Objects.equals(outstockTypeEnum, OutstockTypeEnum.OTHER_OUTSTOCK) || Objects.equals(outstockTypeEnum, OutstockTypeEnum.ASSEMBLE_OUTSTOCK)) {
                    continue;
                }
                BusinessDataDTO businessDataDTO = new BusinessDataDTO();
                BeanUtil.copyProperties(excelTemplateDTO, businessDataDTO);
                if (Objects.equals(outstockTypeEnum, OutstockTypeEnum.CONTRACT_OUTSTOCK)) {
                    Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    map.put("corpid", excelTemplateDTO.getCorpid());
                    map.put("del", 0);
                    map.put("businessType", outstockTypeEnum.getBusinessType());
                    map.put("enable", 1);
                    List<PaasFormEntityExt> paasFormEntityExts = paasFormModel.findEntitys(map);
                    if (CollectionsUtil.isEmpty(paasFormEntityExts)) {
                        continue;
                    }
                    List<Long> formIdList = new ArrayList<>();
                    formIdList.add(-1L);
                    paasFormEntityExts.forEach(paasFormEntityExt -> formIdList.add(paasFormEntityExt.getId()));
                    businessDataDTO.setFormIdList(formIdList);
                    businessDataDTO.setFormId(paasFormEntityExts.get(0).getId());
                } else if (Objects.equals(outstockTypeEnum, OutstockTypeEnum.WORK_ORDER_OUTSTOCK)) {
                    Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    map.put("corpid", excelTemplateDTO.getCorpid());
                    map.put("del", 0);
                    List<WorkOrderFormEntity> paasFormEntityExts = workOrderFormModel.findEntitys(map);
                    if (CollectionsUtil.isEmpty(paasFormEntityExts)) {
                        continue;
                    }
                    List<Long> formIdList = new ArrayList<>();
                    formIdList.add(-1L);
                    paasFormEntityExts.forEach(paasFormEntityExt -> formIdList.add(paasFormEntityExt.getId()));
                    businessDataDTO.setFormIdList(formIdList);
                    businessDataDTO.setFormId(paasFormEntityExts.get(0).getId());
                } else {
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(outstockTypeEnum.getBusinessType(), excelTemplateDTO.getCorpid(), excelTemplateDTO.getDistributorMark(), null);
                    businessDataDTO.setFormId(paasFormEntityExt.getId());
                }

                businessDataDTO.setPageSize(10000);
                businessDataDTO.setSourceBusinessType(excelTemplateDTO.getBusinessType());
                businessDataDTO.setBusinessType(outstockTypeEnum.getBusinessType());
                businessDataDTO.setType(outstockTypeEnum.getCode());
                PaasFormDataEsListVO paasFormDataEsListVO = paasFormDataService.getBusinessDataList(businessDataDTO);
                stockMap.put(itemPoJo.getValue().toString(), paasFormDataEsListVO);
            }
        }
        item.setLinkBusinessMap(stockMap);
    }

    /**
     * 将仓库改成下拉框
     * @param item
     * @param excelTemplateDTO
     */
    private void setCategoryToCombo(FieldAttrEntity item, ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        item.setFieldType(FieldTypeEnum.COMBO.getType());
        List<ItemPoJo> itemPoJoList = new ArrayList<>();
        Map<String, Object> param = BeanUtil.convertBean2Map(excelTemplateDTO, true);
        param.put("orderByStr", "sort ASC, update_time ASC ");
        List<ProductCategoryEntity> productCategoryList = productCategoryModel.findEntitys(param);
        Map<Long, ProductCategoryEntity> categoryMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productCategoryList.forEach(productCategory -> categoryMap.put(productCategory.getId(), productCategory));
        for (ProductCategoryEntity productCategoryEntity : productCategoryList) {
            ItemPoJo itemPoJo = new ItemPoJo();
            String name = concatParentName(categoryMap, productCategoryEntity, new StringBuilder(productCategoryEntity.getName()));
            itemPoJo.setText(name);
            itemPoJo.setValue(productCategoryEntity.getId());
            itemPoJoList.add(itemPoJo);
        }
        item.setItems(itemPoJoList);
    }

    /**
     * 将公司多单位拼到导入模版单位下拉框中
     * @param item
     * @param excelTemplateDTO
     * @throws XbbException
     */
    private void setUnitsToCombo(FieldAttrEntity item, ExcelTemplateDTO excelTemplateDTO) throws XbbException{
        String corpid = excelTemplateDTO.getCorpid();
        List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
//        List<ItemPoJo> itemPoJoList = new ArrayList<>();
//        //先取出原来的单单位
//        List<ItemPoJo> itemPoJos = item.getItems();
//        if(Objects.nonNull(itemPoJos) && itemPoJos.size() > 0){
//            for (ItemPoJo itemPoJo : itemPoJos) {
//                itemPoJoList.add(itemPoJo);
//            }
//        }
//        Map<String, Object> param = BeanUtil.convertBean2Map(excelTemplateDTO, true);
//        param.put("orderByStr", "sort ASC, update_time ASC ");
//        List<ProductUnitGroupEntity> groupEntityList = productUnitGroupDao.findEntities(param);
//        //遍历多单位 将多单位组塞进去
//        for (ProductUnitGroupEntity productUnitGroupEntity : groupEntityList) {
//            ItemPoJo itemPoJo = new ItemPoJo();
//            itemPoJo.setText(productUnitGroupEntity.getName());
//            itemPoJo.setValue(productUnitGroupEntity.getId());
//            itemPoJoList.add(itemPoJo);
//        }
        item.setItems(productItems);
    }

    private String concatParentName(Map<Long, ProductCategoryEntity> categoryMap, ProductCategoryEntity productCategoryEntity, StringBuilder name) {
        ProductCategoryEntity parentCategory = categoryMap.get(productCategoryEntity.getParentId());
        if (parentCategory != null) {
            name = name.insert(0, parentCategory.getName() + "/");
            concatParentName(categoryMap, parentCategory, name);
        }
        return name.toString();
    }

    /**
     * 将错误行数据或重复数据放入列表,并更新ImportStatusPojo
     * @param errorList 存放excel中错误数据列表
     * @param updateList 存放excel中重复数据列表
     * @param rowGroupPojo excel中同一组数据
     * @param e 异常信息
     * @return ImportStatusPojo
     */
    private ImportStatusPojo putToErrorList(List<ErrorExcelDataPojo> errorList,List<ErrorExcelDataPojo> updateList, List<ErrorExcelDataPojo> noSignPersonList,RowGroupPojo rowGroupPojo, Exception e,ImportStatusPojo importStatusPojo) {
        String errorMsg;
        Integer errorCode = 0;
        if (e instanceof XbbException) {
            // xbb异常采用返回的错误信息
            errorMsg = ((XbbException) e).getMsg();
            errorCode = ((XbbException) e).getCode();
        } else {
            LOG.error("导入错误，", e);
            errorMsg = GainPublicErrcodeEnum.DATA_ERROR.getAttr();
        }

        List<ErrorExcelDataPojo> errorExcelDataPojos = new ArrayList<>();
        ErrorExcelDataPojo errorExcelDataPojo = new ErrorExcelDataPojo(errorMsg,rowGroupPojo);
        errorExcelDataPojos.add(errorExcelDataPojo);

        if (errorCode != null && errorCode.equals(SystemErrorCodeEnum.API_ERROR_100034.getCode())) {
            // 是重复数据
            updateList.addAll(errorExcelDataPojos);
            int updateNum = importStatusPojo.getUpdateNum();
            updateNum += rowGroupPojo.getRowValueList().size();
            importStatusPojo.setUpdateNum(updateNum);
        } else if (errorCode != null && errorCode.equals(ImportErrorCodeEnum.API_ERROR_235013.getCode())) {
            noSignPersonList.addAll(errorExcelDataPojos);
            int noSignNum = importStatusPojo.getNoSignNum();
            noSignNum += rowGroupPojo.getRowValueList().size();
            importStatusPojo.setNoSignNum(noSignNum);
        } else if (errorCode != null && errorCode.equals(QuotationErrorCodeEnum.API_ERROR_246002.getCode())) {
            noSignPersonList.addAll(errorExcelDataPojos);
            int noSignNum = importStatusPojo.getNoSignNum();
            noSignNum += rowGroupPojo.getRowValueList().size();
            importStatusPojo.setNoSignNum(noSignNum);
        } else {
            // 错误数据
            errorList.addAll(errorExcelDataPojos);
            int errorNum = importStatusPojo.getErrorNum();
            errorNum += rowGroupPojo.getRowValueList().size();
            importStatusPojo.setErrorNum(errorNum);
        }
        return importStatusPojo;
    }
    /**
     * 通过oss异步下载
     *
     * @param formDataListDTO  导出入参
     * @param exportFormDataVO 导出回参
     * @date 2018年5月10日 下午5:25:12
     * @author 梁鲁江
     */
    @Override
    public String exportAsync(FormDataListDTO formDataListDTO, ExportFormDataVO exportFormDataVO, String suffix) throws XbbException {
        String url;
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();
        String hashKey = corpid + "_" + userId;
        String excelName = "";
        try {
            String name = exportFormDataVO.getName();
            int lastIndexOf = name.lastIndexOf(ImportConstant.EXCEL_SUFFIX);
            name = name.substring(0, lastIndexOf);
            // 过滤url中名称里面的特殊字符
            String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？.]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(name);
            name = m.replaceAll("").trim();
            excelName = name;
            name = corpid + "/" + MD5Util.EncoderByMd5(userId) + "/" + name;
            int size = ossHelper.getListWithPrefixSize(name);
            if (size > 0) {
                name = name + "(" + size + ")";
            }
            LOG.warn("let_me_see_see_exportAsync: " + corpid);
            url = ossHelper.putObjectWorkbook(exportFormDataVO.getWorkbook(), name + ImportConstant.EXCEL_SUFFIX);

            ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(Objects.toString(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), JSON.toJSONString(new ExportStatusPojo())), ExportStatusPojo.class);
            exportStatusPojo.setFinish(3);
            exportStatusPojo.setUrl(url);
            exportStatusPojo.setName(excelName);
            paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);

            PushRefTypePojo.Options options = new PushRefTypePojo.Options();
            options.setDownloadUrl(url);
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(userId), Collections.singletonList(0L), 0, null, I18nMessageUtil.getMessage(StringConstant.EXPORT_SUCCESS), excelName, null, options);
            baseProducer.sendMessage(PushTypeEnum.EXPORT_PUSH, messageRabbitMqDTO);
        } catch (Exception e) {
            LOG.error("导出失败", e);
            ExportStatusPojo exportStatusPojo = JsonHelperUtil.parseObject(Objects.toString(paasRedisHelper.getValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey), JSON.toJSONString(new ExportStatusPojo())), ExportStatusPojo.class);
            exportStatusPojo.setFinish(1);
            exportStatusPojo.setErrorMsg(I18nMessageUtil.getMessage(I18nStringConstant.EXPORT_FAILED));
            paasRedisHelper.setValue(RedisPrefixConstant.EXPORT_STATUS_KEY, hashKey, exportStatusPojo, RedisConstant.SHORT_DURATION);
            PushRefTypePojo.Options options = new PushRefTypePojo.Options();
            MessageRabbitMqDTO messageRabbitMqDTO = new MessageRabbitMqDTO(corpid, Collections.singletonList(userId), Collections.singletonList(0L), 0, null, I18nMessageUtil.getMessage(StringConstant.EXPORT_FAILED), excelName, null, options);
            baseProducer.sendMessage(PushTypeEnum.EXPORT_PUSH_FAIL, messageRabbitMqDTO);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.OSS_UPLOAD_FAILED);
        }
        return url;
    }

    @Override
    public void changeFieldShowTypeForImport(ExcelTemplateDTO excelTemplateDTO, List<FieldAttrEntityForImport> fieldAttrList) {
        Integer distributorMark = excelTemplateDTO.getDistributorMark();
        Integer businessType = XbbRefTypeEnum.transferBusinessType4Distributor(excelTemplateDTO.getBusinessType(), distributorMark);
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        String corpid = excelTemplateDTO.getCorpid();
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                boolean export = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                Integer subBusinessType = excelTemplateDTO.getSubBusinessType();
                fieldAttrList.forEach(item->{
                    if (Objects.equals(item.getAttr(), CustomerManagementEnum.IS_ARCHIVED.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(item.getAttr(), CustomerManagementEnum.PARENT.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if(Objects.equals(item.getAttr(), CustomerManagementEnum.CLUE_ID.getAttr())){
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else  if (Objects.equals(item.getAttr(), CustomerManagementEnum.DISTRIBUTION_DATE.getAttr()) && export) {
                        List<Integer> subBusinessTypes = Arrays.asList(XbbRefTypeEnum.CUSTOMER.getCode(), XbbRefTypeEnum.CUSTOMER_DEAL.getCode(), XbbRefTypeEnum.CUSTOMER_FOLLOW.getCode(), XbbRefTypeEnum.CUSTOMER_FOCUS.getCode());
                        if (Objects.nonNull(subBusinessType) && subBusinessTypes.contains(subBusinessType)) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    } else if (Objects.equals(item.getAttr(), CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr()) && export && Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case CLUE:
                boolean exportFlag = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                Integer subType = excelTemplateDTO.getSubBusinessType();
                fieldAttrList.forEach(item->{
                    if (Objects.equals(item.getAttr(), ClueEnum.IS_ARCHIVED.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }else if (Objects.equals(item.getAttr(), ClueEnum.DISTRIBUTION_DATE.getAttr()) && exportFlag && Objects.equals(subType, XbbRefTypeEnum.ALL_CLUE.getCode())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(item.getAttr(), ClueEnum.BACK_PUBLIC_DATE.getAttr()) && exportFlag && Objects.equals(subType, XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case CONTRACT:
                boolean isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                Boolean isJxcUse = true;
                try {
                    isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                } catch (XbbException e) {
                    e.printStackTrace();
                }
                Boolean finalIsJxcUse = isJxcUse;
                fieldAttrList.forEach(item->{
                    if (Objects.equals(item.getAttr(), ContractEnum.FINISH_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(), ContractEnum.UN_FINISH_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(), ContractEnum.PAY_PERCENT.getAttr())
                            || Objects.equals(item.getAttr(), ContractEnum.INVOICE_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(), ContractEnum.UN_INVOICE_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(),ContractEnum.BAD_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(),ContractEnum.ARCHIVED.getAttr())
                            || (Objects.equals(item.getAttr(), ContractEnum.SHIP_STATUS.getAttr()) && isExport && finalIsJxcUse)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(item.getAttr(), ContractEnum.ADD_PAYMENT.getAttr())) {
                        item.setShowType(ShowTypeEnum.NONE.getCode());
                    }else if (Objects.equals(item.getAttr(), ContractEnum.PRODUCT.getAttr())){
                        if (!finalIsJxcUse) {
                            SubFormPoJo subForm = item.getSubForm();
                            List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)subForm.getItems();
                                fieldAttrEntityList.removeIf(field -> (Objects.equals(field.getAttr(),SelectProductEnum.OUTSTOCK_NUM.getAttr())
                                        || Objects.equals(field.getAttr(),SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())
                                        || Objects.equals(field.getAttr(),SelectProductEnum.RETURN_NUM.getAttr())));
                                subForm.setItems(fieldAttrEntityList);
                        }
                    }
                });
                break;
            case ORDER:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                fieldAttrList.forEach(item->{
                    if (Objects.equals(item.getAttr(), OrderEnum.FINISH_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(), OrderEnum.UN_FINISH_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(), OrderEnum.PAY_PERCENT.getAttr())
                            || Objects.equals(item.getAttr(), OrderEnum.INVOICE_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(), OrderEnum.UN_INVOICE_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(),OrderEnum.BAD_AMOUNT.getAttr())
                            || Objects.equals(item.getAttr(),OrderEnum.ARCHIVED.getAttr())
                            // 出库状态
                            || (Objects.equals(item.getAttr(), OrderEnum.SHIP_STATUS.getAttr()) && isExport)
                            // 订单状态
                            || (Objects.equals(item.getAttr(), OrderEnum.STATUS.getAttr()) && isExport)
                            // 收款状态
                            || (Objects.equals(item.getAttr(), OrderEnum.RECEIVE_PAYMENT_STATUS.getAttr()) && isExport)
                            // 发货状态
                            || (Objects.equals(item.getAttr(), OrderEnum.EXPRESS_STATUS.getAttr()) && isExport)
                            // 下单类型
                            || (Objects.equals(item.getAttr(), OrderEnum.TYPE.getAttr()) && isExport)
                            // 下单人
                            || (Objects.equals(item.getAttr(), OrderEnum.ORDERER.getAttr()) && isExport)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(item.getAttr(), OrderEnum.ADD_PAYMENT.getAttr())) {
                        item.setShowType(ShowTypeEnum.NONE.getCode());
                    } else if (!isExport && (Objects.equals(item.getAttr(), OrderEnum.LINK_CONTACT_NUMBER.getAttr()) || Objects.equals(item.getAttr(), OrderEnum.SHIPPING_ADDRESS.getAttr()))) {
                        // 导入时过滤收货人的联系电话和收货地址
                        item.setShowType(ShowTypeEnum.NONE.getCode());
                    }
                });
                break;
            case ORDER_OUTSTOCK:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                fieldAttrList.forEach(item->{
                    if ((Objects.equals(item.getAttr(), OrderOutStockEnum.EXPRESS_STATUS.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), OrderOutStockEnum.SHIP_DATE.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), OrderOutStockEnum.EXPRESS_DATE.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), OrderOutStockEnum.EXPRESS_NAME.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), OrderOutStockEnum.EXPRESS_NO.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), OrderOutStockEnum.EXPRESS_MEMO.getAttr()) && isExport)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (!isExport && (Objects.equals(item.getAttr(), OrderOutStockEnum.RECEIPT_PHONE.getAttr())
                            || Objects.equals(item.getAttr(), OrderOutStockEnum.RECEIPT_ADDRESS.getAttr())
                            || Objects.equals(item.getAttr(), OrderOutStockEnum.SEND_PHONE.getAttr())
                            || Objects.equals(item.getAttr(), OrderOutStockEnum.SEND_ADDRESS.getAttr()))) {
                        // 导入时过滤收货人和寄件人的联系电话和收货地址
                        item.setShowType(ShowTypeEnum.NONE.getCode());
                    }
                });
                break;
            case RETURN:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                fieldAttrList.forEach(item->{
                    if ((Objects.equals(item.getAttr(), ReturnEnum.ORDER_STATUS.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), ReturnEnum.REFUND_STATUS.getAttr()) && isExport)
//                            || (Objects.equals(item.getAttr(), ReturnEnum.DRAWBACK_STATUS.getAttr()) && isExport)
                            || (Objects.equals(item.getAttr(), ReturnEnum.REFUND_TYPE.getAttr()) && isExport)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case REFUND:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                if (isExport) {
                    try {
                        isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                        if (isJxcUse) {
                            for (FieldAttrEntityForImport item : fieldAttrList) {
                                if (Objects.equals(item.getAttr(), RefundEnum.REFUND_STATUS.getAttr())) {
                                    item.setShowType(ShowTypeEnum.ALL.getCode());
                                    break;
                                }
                            }
                        }else {
                            for (FieldAttrEntityForImport item : fieldAttrList) {
                                if (Objects.equals(item.getAttr(), RefundEnum.PRODUCTS.getAttr())) {
                                    SubFormPoJo subForm = item.getSubForm();
                                    List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)subForm.getItems();
                                    fieldAttrEntityList.removeIf(field -> (Objects.equals(field.getAttr(), SelectProductEnum.SOURCE_DOC.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.INSTOCK_NUM.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.WAIT_INSTOCK_NUM.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.BATCH.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.GUARANTEE_PERIOD.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.PRODUCE_DATE.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.EXPIRE_DATE.getAttr())
                                            || Objects.equals(field.getAttr(), RefundProductEnum.COST.getAttr())));
                                    subForm.setItems(fieldAttrEntityList);
                                    break;
                                }
                            }
                        }
                    } catch (XbbException e) {
                        e.printStackTrace();
                    }
                }
                break;
                //移除供应商导入模版中的单位字段
            case SUPPLIER:
                Boolean isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if(isImport){
                    for (FieldAttrEntityForImport item : fieldAttrList) {
                        if (Objects.equals(item.getAttr(), RefundEnum.PRODUCTS.getAttr())) {
                            SubFormPoJo subForm = item.getSubForm();
                            List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)subForm.getItems();
                            fieldAttrEntityList.removeIf(field -> (Objects.equals(field.getAttr(), SelectProductEnum.UNIT.getAttr())));
                            subForm.setItems(fieldAttrEntityList);
                            break;
                        }
                    }
                }
                break;
                //移除BOM单导入模版中的单位字段
            case BOM_BILL:
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if(isImport){
                    for (FieldAttrEntityForImport item : fieldAttrList) {
                        if (Objects.equals(item.getAttr(), BomBillEnum.PRODUCT.getAttr()) || Objects.equals(item.getAttr(), BomBillEnum.MATERIEL.getAttr())) {
                            SubFormPoJo subForm = item.getSubForm();
                            List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)subForm.getItems();
                            fieldAttrEntityList.removeIf(field -> (Objects.equals(field.getAttr(), SelectProductEnum.UNIT.getAttr())));
                            subForm.setItems(fieldAttrEntityList);
                        }
                    }
                }
                break;
            case RETURNED_PURCHASE:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                if (isExport) {
                    for (FieldAttrEntityForImport item : fieldAttrList) {
                        if (Objects.equals(item.getAttr(), ReturnedPurchaseEnum.RETURNED_STATUS.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                            break;
                        }
                    }
                }
                break;
            case TRANSFER:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                if (isExport) {
                    for (FieldAttrEntityForImport item : fieldAttrList) {
                        if (Objects.equals(item.getAttr(), TransferEnum.TRANSFER_STATUS.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                            break;
                        }
                    }
                }
                break;
            case INVENTORY:
                isExport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT);
                if (isExport) {
                    for (FieldAttrEntityForImport item : fieldAttrList) {
                        if (Objects.equals(item.getAttr(), InventoryEnum.INVENTORY_STATUS.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                            break;
                        }
                    }
                }
                //移除盘点单导入模版中的单位字段
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if(isImport){
                    for (FieldAttrEntityForImport item : fieldAttrList) {
                        if (Objects.equals(item.getAttr(), InventoryEnum.PRODUCT.getAttr())) {
                            SubFormPoJo subForm = item.getSubForm();
                            List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)subForm.getItems();
                            fieldAttrEntityList.removeIf(field -> (Objects.equals(field.getAttr(), SelectProductEnum.UNIT.getAttr())));
                            subForm.setItems(fieldAttrEntityList);
                            break;
                        }
                    }
                }
                break;
            case SALES_OPPORTUNITY:
                fieldAttrList.forEach(item->{
                    if (Objects.equals(item.getAttr(), SalesOpportunityEnum.LAST_CONNECT_TIME.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                    // 关联竞争对手和赢单竞品不支持导入
                    if (Objects.equals(item.getAttr(), SalesOpportunityEnum.LINK_COMPETITOR.getAttr())) {
                        item.setShowType(ShowTypeEnum.EXPORT_NO_IMPORT.getCode());
                    }
                    if (Objects.equals(item.getAttr(), SalesOpportunityEnum.WIN_COMPETITOR.getAttr())) {
                        item.setShowType(ShowTypeEnum.EXPORT_NO_IMPORT.getCode());
                    }
                });
                break;
            case PRODUCT:
                fieldAttrList.forEach(item -> {
                    if (Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(item.getAttr(), ProductEnum.ONLINE.getAttr()) && Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(item.getAttr(), ProductEnum.STOCK_NOTIFY.getAttr()) || Objects.equals(item.getAttr(), ProductEnum.IS_NOTIFY.getAttr())) {
                        item.setShowType(ShowTypeEnum.NONE.getCode());
                    } else if (Objects.equals(item.getAttr(), ProductEnum.STOCK.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(excelTemplateDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode()) && Objects.equals(item.getAttr(), ProductEnum.WAREHOUSE.getAttr())) {
                        item.setShowType(ShowTypeEnum.NONE.getCode());
                    } else if (Objects.equals(item.getAttr(), ProductEnum.ONLINE_TIME.getAttr()) && Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case PURCHASE:
                boolean unImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if (!unImport) {
                    fieldAttrList.forEach(item -> {
                        if ( Objects.equals(item.getAttr(), PurchaseEnum.FINISH_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.UN_FINISH_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.RECEINE_PERCENT.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.INVOICE_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.UN_INVOICE_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.BAD_AMOUNT.getAttr())
                                ||Objects.equals(item.getAttr(), PurchaseEnum.RECEIVE_STATUS.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        } else if ( Objects.equals(item.getAttr(), PurchaseEnum.ADD_PAYPLAN.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.ADD_PAY_SHEET.getAttr())
                                || Objects.equals(item.getAttr(), PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr())) {
                            item.setShowType(ShowTypeEnum.NONE.getCode());
                        }
                    });
                }
                break;
            case PAYMENT:
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if (isImport) {
                    fieldAttrList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), PaymentEnum.OWNER_ID.getAttr()) || Objects.equals(item.getAttr(), PaymentEnum.REAL_PAY_TIME.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    });
                } else {
                    fieldAttrList.forEach(item -> {
                        boolean flag = Objects.equals(item.getAttr(), PaymentEnum.OWNER_ID.getAttr()) || Objects.equals(item.getAttr(), PaymentEnum.COUSERID.getAttr()) || Objects.equals(item.getAttr(), PaymentEnum.REAL_PAY_TIME.getAttr()) || Objects.equals(item.getAttr(), PaymentEnum.RECEIVABLE_PERIOD.getAttr()) || Objects.equals(item.getAttr(), PaymentDistributorEnum.ORDERER.getAttr());
                        if (flag) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    });
                }
                break;
            case PAY_PLAN:
                fieldAttrList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), PayPlanEnum.OWNER_ID.getAttr()) || Objects.equals(item.getAttr(), PayPlanEnum.REAL_PAY_TIME.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case QUOTATION:
                fieldAttrList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), QuotationEnum.GROUP_NUMBER.getAttr()) || Objects.equals(item.getAttr(), QuotationEnum.VERSION.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                    if (Objects.equals(item.getAttr(), QuotationEnum.QUOTATION_NO.getAttr())) {
                        item.setShowType(ShowTypeEnum.LIST.getCode());
                    }
                });
                break;
            case COMMUNICATE_PLAN:
                fieldAttrList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), CommunicatePlanEnum.STATUS.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case PAYMENT_SHEET:
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if (!isImport) {
                    fieldAttrList.forEach(item->{
                        if (Objects.equals(item.getAttr(), PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr())
                                || Objects.equals(item.getAttr(), PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PaymentSheetEnum.INVOICE_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PaymentSheetEnum.OWNER_ID.getAttr())
                                || Objects.equals(item.getAttr(), PaymentSheetEnum.COUSERID.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    });
                } else if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    fieldAttrList.forEach(item->{
                        if (Objects.equals(item.getAttr(), PaymentSheetDistributorEnum.PAY_METHOD.getAttr())) {
                            item.setShowType(ShowTypeEnum.NONE.getCode());
                        }
                    });
                }
                break;
            case PAY_SHEET:
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if (!isImport) {
                    fieldAttrList.forEach(item->{
                        if (Objects.equals(item.getAttr(), PaySheetEnum.PAY_SHEET_TYPE.getAttr())
                                || Objects.equals(item.getAttr(), PaySheetEnum.WRITE_OFF_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PaySheetEnum.INVOICE_AMOUNT.getAttr())
                                || Objects.equals(item.getAttr(), PaySheetEnum.OWNER_ID.getAttr())
                                || Objects.equals(item.getAttr(), PaySheetEnum.COUSERID.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    });
                }
                break;
            case PAYMENT_TASK:
                fieldAttrList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), PaymentTaskEnum.STATUS.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case SEQ_SEARCH:
                fieldAttrList.forEach(item->{
                    if (Objects.equals(item.getAttr(), ProductSerialBalanceEnum.SEQ.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    } else if (Objects.equals(item.getAttr(), ProductSerialBalanceEnum.STATUS.getAttr())) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            case OTHER_INCOME:
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if (!isImport) {
                    fieldAttrList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    });
                }
                break;
            case OTHER_EXPENSE:
                isImport = Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_IMPORT);
                if (!isImport) {
                    fieldAttrList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr())) {
                            item.setShowType(ShowTypeEnum.ALL.getCode());
                        }
                    });
                }
                break;
            case SERVICE_PROJECT:
                fieldAttrList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), "date_1")
                            && Objects.equals(excelTemplateDTO.getFormImportOrExport(), ImportConstant.FROM_EXPORT)) {
                        item.setShowType(ShowTypeEnum.ALL.getCode());
                    }
                });
                break;
            default:
                break;
        }
    }

    @Override
    public List<RowGroupPojo> getPaasExcelValue(Workbook workBook, int startRowIndex, List<FieldAttrEntityForImport> fieldAttrList, List<CellTitlePojo> titlePojoList) throws XbbException {
        try {
            Sheet sheet = workBook.getSheetAt(0);
            List<RowGroupPojo> valueList = new ArrayList<>();
            for (int rowIndex = startRowIndex; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (ExcelUtil.isEmptyRow(row)) {
                    continue;
                }
                Integer uniqueIdentityColumnIndex = null;
                out:
                for (FieldAttrEntityForImport item : fieldAttrList) {
                    if (Objects.equals(item.getNoRepeat(), 1)) {
                        String attrName = item.getAttrName();
                        for (CellTitlePojo titlePojo : titlePojoList) {
                            if (Objects.equals(titlePojo.getTitle(), attrName)) {
                                uniqueIdentityColumnIndex = titlePojo.getColumnIndex();
                                break out;
                            }
                        }
                    }
                }
                String groupTagValue = null;
                List<CellValuePojo> valuePojoList = new ArrayList<>();
                for (CellTitlePojo titlePojo : titlePojoList) {
                    Cell cell = row.getCell(titlePojo.getColumnIndex());
                    String cellValue = ExcelUtil.getCellValue(cell);
                    if (Objects.equals(uniqueIdentityColumnIndex, titlePojo.getColumnIndex())) {
                        groupTagValue = cellValue;
                    }
                    CellValuePojo cellValuePojo = new CellValuePojo(cellValue, titlePojo.getTitle(),titlePojo.getParentTitle(), titlePojo.getSecondParentTitle(), titlePojo.getThirdParentTitle(),  titlePojo.getColumnIndex());
                    valuePojoList.add(cellValuePojo);
                }

                RowGroupPojo rowGroupPojo = importHelper.getGroupByUniqueTag(valueList, groupTagValue);
                if (Objects.isNull(rowGroupPojo)) {
                    rowGroupPojo = new RowGroupPojo(groupTagValue);
                    valueList.add(rowGroupPojo);
                }
                rowGroupPojo.getRowValueList().add(valuePojoList);
            }
            return valueList;
        } catch (Exception e) {
            LOG.error("ExcelOperatorService导入数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 导出时，特殊处理字段的 showType
     */
    private void specialHandleShowType4Export(Integer formImportOrExport, Integer businessType, List<FieldAttrEntityForImport> fieldAttrList){
        /**
         * 生产单、销项发票、进项发票的表单解释在导出时，fileType 为 NUM和COMBO_NUM，特出处理
         * 生产单：num_1,num_2,num_3
         * 销项发票：num_3,num_5
         * 进项发票：num_2,num_3
         */
        List<String> productionOrderFieldList = ProductionOrderEnum.getExportNumAttrList();
        List<String> invoiceFieldList = Arrays.asList(InvoiceEnum.IS_RED.getAttr(),InvoiceEnum.IS_CANCEL.getAttr());
        List<String> purchaseInvoiceFieldList = Arrays.asList(PurchaseInvoiceEnum.IS_RED.getAttr(),PurchaseInvoiceEnum.IS_CANCEL.getAttr());
        if(Objects.equals(formImportOrExport,ImportConstant.FROM_EXPORT) && CollectionsUtil.isNotEmpty(fieldAttrList) && Objects.nonNull(businessType)){
            for(FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList){
                String attr = fieldAttrEntityForImport.getAttr();
                if(scoreRuleHelp.isScoreField(businessType,attr)){
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode()) && Objects.equals(attr, DistributorAccountEnum.ACCOUNT_STATUS.getAttr())) {
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_LIMIT.getCode()) && Objects.equals(attr, CreditLimitEnum.STATUS.getAttr())) {
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode()) && Objects.equals(attr, CreditTemporaryLimitEnum.APPLY_STATUS.getAttr())) {
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode()) && productionOrderFieldList.contains(attr)){
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.INVOICE.getCode()) && invoiceFieldList.contains(attr)){
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INVOICE.getCode()) && purchaseInvoiceFieldList.contains(attr)){
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                } else if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) && (Objects.equals(attr,SalesOpportunityEnum.LINK_COMPETITOR.getAttr()) || Objects.equals(attr,SalesOpportunityEnum.WIN_COMPETITOR.getAttr()))){
                    fieldAttrEntityForImport.setShowType(ShowTypeEnum.ALL.getCode());
                }
            }
        }
    }

    /**
     * 所在地区excel内下拉框解析
     * @param item
     * @param excelTemplateDTO
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/1/18 14:32
     * @version 1.0
     */
    private void setAreaToCombo(FieldAttrEntity item, ExcelTemplateDTO excelTemplateDTO) throws XbbException {
        item.setFieldType(FieldTypeEnum.COMBO.getType());
        List<ItemPoJo> itemPoJoList = new ArrayList<>();
        Map<String, Object> param = BeanUtil.convertBean2Map(excelTemplateDTO, true);
        param.put("orderByStr", "sort ASC, update_time ASC ");
        List<DistributorAreaEntity> areaEntityList = distributorAreaModel.findEntities(param);
        Map<Long, DistributorAreaEntity> areaMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        areaEntityList.forEach(areaEntity -> areaMap.put(areaEntity.getId(), areaEntity));
        for (DistributorAreaEntity distributorAreaEntity : areaEntityList) {
            ItemPoJo itemPoJo = new ItemPoJo();
            String name = concatParentName(areaMap, distributorAreaEntity, new StringBuilder(distributorAreaEntity.getName()));
            itemPoJo.setText(name);
            itemPoJo.setValue(distributorAreaEntity.getId());
            itemPoJoList.add(itemPoJo);
        }
        item.setItems(itemPoJoList);
    }

    /**
     * 拼接名称
     * @param areaMap
     * @param distributorAreaEntity
     * @param name
     * @return java.lang.String
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/1/18 14:49
     * @version 1.0
     */
    private String concatParentName(Map<Long, DistributorAreaEntity> areaMap, DistributorAreaEntity distributorAreaEntity, StringBuilder name) {
        DistributorAreaEntity area = areaMap.get(distributorAreaEntity.getParentId());
        if (area != null) {
            name = name.insert(0, area.getName() + "/");
            concatParentName(areaMap, area, name);
        }
        return name.toString();
    }
}
